In a class that contains an inheritance relationship, a derived class object is generated, and the constructor is called to initialize the object, and the order of the constructors is called first the constructor of the topmost base class, the second top level .... But there are differences in common inheritance and virtual inheritance.
- Normal Inheritance: The parent class can only be initialized by its direct derived class
1 classA2 {3 CharA;4 Public:5AChar_a): A (_a) {cout << a <<Endl;}6 };7 8 classB: PublicA9 {Ten Charb; One Public: ABChar_a,Char_b): A (_a), B (_b) {cout << b <<Endl;} - }; - the classC: PublicA - { - CharC; - Public: +CCharAarChar_c): A (_a), C (_c) {cout << c <<Endl;} - }; + A classD: PublicB PublicC at { - CharD; - Public://Note the initialization list, the parent class can only be initialized by its direct derived class, if the initialization list is: A (_a), B (_b), C (_c), D (_d), then an error occurs -DChar_a,Char_b,Char_c,Char_d): B (_a,_b), C (_a,_c), D (_d) {cout << D <<Endl;} - }; - in voidMain () - { toD D ('A','B','C','D'); +}
Virtual Inheritance:
The base class can only be initialized by the bottommost derived class, not by the direct base class, because virtual inheritance is to avoid multiple inheritance, only one child object can be initialized, and in multiple inheritance, a base class may have multiple direct derived classes, in order to avoid the direct derived class to initialize the base class more than once. Can only be initialized by the lowest-level derived class.
1 classA2 {3 CharA;4 Public:5AChar_a): A (_a) {cout << a <<Endl;}6 };7 8 classD |Virtual PublicA9 {Ten Charb; One Public: ABChar_a,Char_b): A (_a), B (_b) {cout << b <<Endl;} - }; - the classE |Virtual PublicA - { - CharC; - Public: +CCharAarChar_c): A (_a), C (_c) {cout << c <<Endl;} - }; + A classD: PublicB PublicC at { - CharD; - Public://The initialization list contains a (_a), which indicates that the virtual base class is initialized by the bottommost derived class -DChar_a,Char_b,Char_c,Char_d): A (_a), B (_a,_b), C (_a,_c), D (_d) {cout << D <<Endl;} - }; - voidMain () in { -D D ('A','B','C','D'); to}
The bottom of the story here is the level of the object.
such as b b, B is the bottom-most derived class of a, and B is responsible for initializing the sub-object of a contained in B
D, D is the lowest derived class of a, and D is responsible for initializing the child object of a.
The initialization problem of virtual base class