Multiple inheritance in C + + inevitably occurs with diamond inheritance, that is, the two base classes of inheriting classes are also inherited classes of the same base class, and when an object is created, what order do they call the constructor?
If virtual inheritance is not performed:
classbase{ Public: Base () {cout<<"base default constructor call"<<Endl; } Base (inti) {cout<<"Base parameter constructor call"<<Endl; cout<<i<<Endl; } Virtual~Base () {}};classBASE1: Publicbase{ Public: Base1 (intIintj=0): Base (j) {cout<<"Base1 parameter constructor call"<<Endl; cout<<i<<Endl; } Virtual~Base1 () {}};classBASE2: Publicbase{ Public: Base2 (inti): Base (i) {cout<<"Base2 parameter constructor call"<<Endl; cout<<i<<Endl; } Virtual~Base2 () {}};classDriveD: PublicBASE1, Publicbase2{ Public: drived (intAintBintCintd): Base1 (a), Base2 (b) {}Virtual~drived () {}};
Run result of new object:
Virtual Inheritance (the constructor call to base in Base1 Base2 in virtual inheritance no longer works, the call of the base constructor is directly responsible for the derived class, and if DriveD is not explicitly stated, the default parameterless constructor is called):
classbase{ Public: Base () {cout<<"base default constructor call"<<Endl; } Base (inti) {cout<<"Base parameter constructor call"<<Endl; cout<<i<<Endl; } Virtual~Base () {}};classBASE1:Virtual Publicbase{ Public: Base1 (intIintj=0): Base (j) {cout<<"Base1 parameter constructor call"<<Endl; cout<<i<<Endl; } Virtual~Base1 () {}};classBASE2:Virtual Publicbase{ Public: Base2 (inti): Base (i) {cout<<"Base2 parameter constructor call"<<Endl; cout<<i<<Endl; } Virtual~Base2 () {}};classDriveD: PublicBASE1, Publicbase2{ Public: drived (intAintBintCintd): Base1 (a), Base2 (b) {}Virtual~drived () {}};
The result of running the new object:
If the DriveD class has member functions of the BASE1 BASE2 type:
class DriveD: public Base1, public base2{public: Base1 mem1; Base2 mem2; DriveD (int A,int b,int c,int D): Base1 (a), Base2 (b), Mem1 (c), MEM2 (d) { } virtual ~drived () {}};
The result of running the new object
If you specify the constructor of base in the derived class:
class DriveD: public Base1, public base2{public: Base1 mem1; Base2 mem2; DriveD (int A,int b,int c,int D): Base1 (a), Base2 (b), Base (a), mem1 (c), mem2 (d) { } virtual ~drived () {}};
Then run the result:
C + + multiple inheritance, call order of constructors in diamond inheritance