Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor order in virtual inheritance

Tags:

c++

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: enter image description herestructure 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.

like image 384
XiaJun Avatar asked Mar 16 '12 12:03

XiaJun


1 Answers

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:

  1. direct bases are constructed in the order they're listed (unless they're a virtual base that has been constructed already),
  2. bases are constructed before the class's own constructor runs.

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.

like image 195
Steve Jessop Avatar answered Oct 03 '22 06:10

Steve Jessop