Multiple inheritation constructor initialization

Jan 7, 2016 at 7:06pm
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 : virtual public A{}
class C : virtual public 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){}
Last edited on Jan 7, 2016 at 7:06pm
Jan 7, 2016 at 7:27pm
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().

cppreference has a summary http://en.cppreference.com/w/cpp/language/initializer_list#Initialization_order
Jan 7, 2016 at 7:57pm
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?
Jan 7, 2016 at 9:15pm
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.

special rule: 1st example, A is initialized by D
Jan 7, 2016 at 9:17pm
every base class is initialized by the class that directly derives from it, except that virtual bases are initialized by the most derived class.
This. Thank you!
And what happens for virtual classes derived from virtual?
Last edited on Jan 7, 2016 at 9:18pm
Jan 7, 2016 at 9:57pm
both are initialized directly by the most derived class (depth-first order)
Topic archived. No new replies allowed.