2

I am getting a jumbled output for the below program.

#include<iostream>

using namespace std;

class A
{
    int x;

    public:
        A()
        {
            cout << "A() " << endl;
        }

};

class B : virtual public A
{
    int y;

    public:
        B()
        {
            cout << "B() " << endl;
        }
};

class C : public A
{
    int z;

    public:
        C()
        {
            cout << "C() " << endl;
        }
};

class D1 : public B , public C
{
    int j;

    public:
        D1()
        {
            cout << "D1() " << endl;
        }
};

class D2 : public C, public B
{
    int k;

    public:
        D2()
        {
            cout << "D2() " << endl;
        }
};

int main()
{
    D1 d1;
    D2 d2;
    return 0;
}

The above code prints the output as below.

A() B() A() C() D1() A() A() C() B() D2()

Where as I was expecting the output as

A() B() A() C() D1() A() C() A() B() D2()

due to the sequence in which I have inherited from the base classes.

It seems that the virtual keyword is responsible for jumbling the output.

Can someone please elaborate why is the above behavior when using virtual here.

Krishna Oza
  • 1,390
  • 2
  • 25
  • 50
  • I my be wrong but why don't you call the constructors of the parent class "initialization_list" style?. Like so: D2():C(), B() { cout << "D2() " << endl;}. I imagine it will give you greater control and will enlist your compiler to help you if you mess up the order of stuff. I know this won't answer the virtual thing (see the duplicate question) but can help. – The Marlboro Man Sep 09 '16 at 10:41
  • @TheMarlboroMan correct that is one way out of the problem , but the question was to determine the behavior. – Krishna Oza Sep 09 '16 at 10:43
  • Perhaps these might help http://stackoverflow.com/questions/10534228/order-of-constructor-call-in-virtual-inheritance , http://www.parashift.com/c++-faq-lite/multiple-inheritance.html#faq-25.11 . Both deal with virtual inheritance and calling order of the constructors. – The Marlboro Man Sep 09 '16 at 11:00

0 Answers0