The output of the program below is: 5 5
#include <iostream>
using namespace std;
struct A
{
public:
int myInt;
A(int n): myInt(n){}
A(): myInt(5) {}
};
class B : virtual public A
{
public:
B(int n):A(10) {}
B():A(10) {}
};
class C : virtual public A
{
public:
C(int n):A(3*n) {}
};
class D : public B, public C
{
public:
D(int n=90) : C(2*n), B(n) {}
};
class E : public D
{
public:
E(int n=20):D(n-1) {}
};
int main()
{
D d(100);
cout << d.myInt << endl;
E e;
cout << e.myInt << endl;
return 0;
}
Consider the object d
. From what I understand the inheritance is constructed based on the order of the inheritance list (rather than the initialization list) so B
class is constructed first with the param 100
which goes to class A
with the parameter 10
. So now A
sets myInt
to the value 10
. The same goes for Class c
and because myInt
is virtual then it is set to the number 600
. I never expected 5
. why is this happening?