The sequence of constructor calls in multiple inheritance

I tried to find a lot, what if only one class is created virtual with multiple inheritance ? In this case, the behavior of the constructor call is not clear to me. Say for example the code -

#include<iostream> using namespace std; class grand{ public: grand(){cout<<"grandfather"<<endl;} }; class parent1:virtual public grand{ //virtual used only here public: parent1(){cout<<"parent1 "<<endl;} }; class parent2: public grand{ public: parent2(){cout<<"parent2"<<endl;} }; class child:public parent1,public parent2{ public: child(){cout<<"child"<<endl;} }; int main() { child s; return 0; } 

The output of this code is as

 grandfather parent1 grandfather parent2 child 

but in the above code if we change this

 class parent1:virtual public grand{ public: parent1(){cout<<"parent1 "<<endl;} }; class parent2: public grand{ public: parent2(){cout<<"parent2"<<endl;} }; 

to that

 class parent1:public grand{ //virtual removed from here public: parent1(){cout<<"parent1 "<<endl;} }; class parent2:virtual public grand{ //virtual is added here public: parent2(){cout<<"parent2"<<endl;} }; 

output is displayed as

 grandfather grandfather //why parent1 constructor is not called here? parent1 parent2 child 

Does it bother me why the parent constructor is not called after grandfather?

+5
source share
1 answer

The standard says [C ++ 11, section 12.6.2 / 10] that:

In the non-delegated constructor, initialization continues in the following order:

- Firstly, and only for the constructor of the derived class itself, the virtual base classes are initialized in the order they appear on the first class from left to right directed acyclic graph base classes, where "from left to right" is the order in which the base classes appear in the base specifier of the derived class.

- Then direct base classes are initialized in the order of declaration as they appear in the list-specifier-base (regardless of the order of the MEM-initializers).

- Then non-static data elements are initialized in the order in which they were declared in the class definition (again, regardless of the order of the MEM initializers).

- Finally, the compound instruction of the constructor body is executed.

So, your virtual base classes are always created first ... This is really important when sharing a virtual base class.

+5
source

Source: https://habr.com/ru/post/1208937/


All Articles