I read that in virtual inheritance, constructors are called "from the most derived". consider the following code. In my opinion, the most derived class here is D. then B and C and the "most-not-derived" is A. So how come the most "Base" constructor is called first and not the "most derived"? Thanks.
#include <iostream>
using namespace std;
struct A
{
A()
{
cout << "A default constructor" << endl;
}
};
struct B : virtual public A
{
B() : A()
{
cout << "B default constructor" << endl;
}
};
struct C : virtual public A
{
C() : A()
{
cout << "C default constructor" << endl;
}
};
struct D : public B, public C
{
D() : B(), C()
{
cout << "D default constructor" << endl;
}
};
int main()
{
D d;
}
This is the output :
A default constructor
B default constructor
C default constructor
D default constructor
UPDATE:
Ok. so consider the following code. Notice that 10 was printed although D,B and C constructors sent 7. Here actually the base class IS the first one that is called. There was no chain from D to B to A. A() was called first (actually it's default constructor). and only then B and C constructors were called.
But I read : "from the most derived." Source : c++ virtual inheritance
the most derived here is D then B and C and only then A. So how come that A is called first without even considering the parameters B,D,C transfer to it from their constructors ? Thanks.
The code :
#include <iostream>
using namespace std;
struct A
{
int _x;
A()
{
_x = 10;
cout << "A default constructor" << endl;
}
A(int x)
{
_x = x;
cout << "A NOT-default constructor" << endl;
}
};
struct B : virtual public A
{
B(int x=7) : A(x)
{
cout << "B constructor" << endl;
}
};
struct C : virtual public A
{
C(int x=7) : A(x)
{
cout << "C constructor" << endl;
}
};
struct D : public B, public C
{
D(int x=7) : B(x), C(x)
{
cout << "D constructor" << endl;
}
};
int main()
{
D d;
cout << d._x;
}
The output :
A default constructor
B constructor
C constructor
D constructor
10