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?
source share