Reputation: 2002
If I have something like
class Base1 {};
class Base2 {};
class Derived : public Base1, public Base2 {};
Then order of constructor call on making object of Derived is
Base1
Base2
i.e in the order they appear in
class Derived : public Base1, public Base2 {};
But If I change it to class Derived : public Base1, virtual public Base2 {}; Then Order of constructor call becomes
Base2
Base1
I am not able to understand why this is so ?
Another simple doubt: what can be the meaning and purpose of inheriting Base1 virtually.
Upvotes: 1
Views: 171
Reputation: 791551
Those are just the rules. The most derived class being constructed initializes all the virtual base classes in the hierarchy first before starting the initialization of its non-virtual direct bases.
The rules come from the standard (ISO/IEC 14882:2011), section 12.6.2 [class.base.init] / 10.
A rationale for this approach would be that it ensures that all base classes are initialized before their derived classes whether or not they are virtual bases.
Upvotes: 4
Reputation: 208323
On the order of initialization, Charles has already answered properly: those are the rules, first the virtual bases in the order of declaration, then the non-virtual bases in the order of declaration, then member variables in the order of declaration.
What is the meaning of virtual inheritance? It means that your object derives from that particular base, but that if in a hierarchy more than one subobjects (bases of the complete type) inherit virtually from the same base type, only one base subobject will be present. You can read the virtual
keyword there as I am willing to share my base
with other objects in the complete type.
struct ubase {};
struct sbase {};
struct A : ubase, virtual sbase {}; // has a sbase subobject, but is willing to share..
struct B : ubase, virtual sbase {}; // ... but want to have my own ubase
struct C : A, B {}; // only one sbase subobject, shared by A and B
// ... but two ubase subobjects, A::ubase and B::ubase
As per the second question, when do you want to use virtual inheritance? Whenever in a type hierarchy you might end up inheriting from the same base more than once and in your design all those occurrences of the base class are just one. In general, it is quite uncommon to use virtual inheritance other than in a few particular cases.
Upvotes: 3
Reputation: 733
As for inheriting virtually. It comes into play when you have a derived class like below
class A {};
class B : public virtual A {} ;
class C : public virtual A {} ;
class D : B, C { } // this class has only one instance of A!
aka the diamond problem!
Upvotes: 1