I'm studying C++, and I came to virtual inheritance and derived class initialization. So I have something like this:
1 2 3 4 5 6
class A{}
class B : virtualpublic A{}
class C : virtualpublic A{}
class D : public B, public C{}
// D's constructor, here I have to initialize A's constructor (even if B and C are supposed to do this) or the default one will be called
D::D(int x) : B(x), C(x), A(x){}
This is multiple inheritation initialization, but what if I have 2 not common-derived classes like:
1 2 3 4 5 6 7
class A{}
class A1{}
class B : public A{}
class C : public A1{}
class D : public B, public C{}
// D's constructor, assuming that B has to call A's constructor (like above) and C has to call A1's constructor, will they effectively get called?
D::D(int x) : B(x), C(x){}
Your first example is the exception; all virtual base constructors, gathered from the entire inheritance lattice in depth-first left-to-right order, run before the most derived constructor does anything .
For everything else, each constructor simply forces its direct bases to construct, left to right, before doing anything else; so before D constructor runs, it calls B(x), which (before it itself can run) calls A(), and then (still before running its own constructor) D calls C(x), which calls A1().
So, from what I undestood: everything is intialized as it is supposed to be, except for the virtually inherited class (like in my first example: A) for which gets called the default constructor if nothing is specified. Am I right?
not sure what you mean by "for which gets called the default constructor if nothing is specified" - that's true for any base class initialization.
Let me rephrase, every base class is initialized by the class that directly derives from it, except that virtual bases are initialized by the most derived class.
normal rule: 1st example, B is initialized by D, C is initiailized by D. 2nd example A is initialized by B, A1 is initialized by C, B is initialized by D, C is initialized by D.