Ii. derived classes with inline objects
1. In general, we will define constructors like this
int string int string int sid): Person (i, NAM), parent (Pid,pnam) {stuid = SID;}
The person is the constructor of the base class, and the parent is the person child object that is embedded in the derived class
2. Specific examples
1#include <iostream>2 using namespacestd;3 classA4 {5 intDataa;6 Public:7AintA):d Ataa (a) {cout <<"call A's constructor"<<Endl;}8 };9 classD | PublicATen { One intDatab; A A A1; - Public: -Bint,int,int); the }; b::b (int A, int B, int c): A (a), A1 (B) {datab = c; cout << " Call B's constructor " << Endl;} - voidMain () - { +cout <<"***************************"<<Endl; -cout <<"Crazy_henry's Demo:"<< endl<<Endl; +b b (1,2,3); A}
Execution Result:
Further, no matter how the order in the parameter table changes, as long as it conforms to the written specification, it can be executed, and the order of execution:(1) The constructor of the base class (2) The derived class of the embedded base class object (3) The new data member (4) function body of the derived class
For example, the following statement completely disrupts the original order:
B::B (intintint" call B's constructor " << Endl;}
3. Inheritance and embedding between three classes
The above analysis is the inheritance and embedding between the two classes, which is actually the same:
1#include <iostream>2 using namespacestd;3 classA4 {5 intDataa;6 Public:7AintA):d Ataa (a) {cout <<"call A's constructor"<<Endl;}8 };9 classCTen { One intDatac; A Public: -Cintc):d Atac (c) {cout <<"Call C's constructor"<<Endl;} - }; the classD | PublicA - { - intDatab; - C C1; + Public: -Bint,int,int); + }; b::b (int A, int B, int c):d Atab (b), C1 (c), a (a) {cout << With B's constructor " << Endl;} at - voidMain () - { -cout <<"***************************"<<Endl; -cout <<"Crazy_henry's Demo:"<< endl<<Endl; -b b (1,2,3); in}
However, it is important to note that before defining B, it is important to write the definition of C in the front of B, otherwise, the C inline object of B is not recognized!
4. When multiple objects are embedded at the same time, there is also an explicit invocation of the object's constructor and the implicit invocation of the object's constructor, detailed analysis I wrote in another about the composition of the constructor of the class it wrote
The constructor of the "C + + Learning path" derived class (II)