I am a freshman in C++, especially about object-oriented programming. And now I have a problem during my learning.
There is a class hierarchy following:
class Class{};
class Base:public Class{};
class Derived1:virtual public Base{};
class Derived2:virtual public Base{};
class MI:public Derived1,public Derived2{};
class Final:public MI,public Class{};
And now I want to know what the order of constructor for the definition of a Final class object is.
I draw a diagram: structure of class inheritance http://hi.csdn.net/attachment/201203/16/2712336_1331902452BziD.jpg
I know Virtual base classes are always constructed prior to nonvirtual base classes regardless of where they appear in the inheritance hierarchy. What I am confused is that if constructor of class Class is before Base, and if constructor of Class is invoked twice. And why?
Can someone tell my the answer? The more detailed, the better.
The direct inheritance of Class
by Final
and Base
is not virtual
, so an instance of Final
has two base class subobjects of type Class
. The one that is the direct base of Base
is constructed before Base
, and the one that is the direct base of Final
is constructed afterwards (in fact after MI
).
The reason is that:
Applying (1) to Final
tells us that Class
is constructed after MI
. Applying (2) several times tells us that Class
is constructed before Base
, before Derived1
and Derived2
, before MI
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With