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.