The constructor of a simple derived class:
1. The so-called simple derived class refers to derived classes that do not contain inline objects of the base class.
2. In general, the constructor of such a derived class is in the form of:
int string int sid): Person (i, nam) {stuid = SID;}
Person (is the base class's initialization list )
3. Use of initialization lists for constructors
3.1 All constructors can take an initialization table of parameters to construct data members that belong to them entirely , such as:
1#include <iostream>2 using namespacestd;3 classA4 {5 Public:6AintA):d Ataa (a) {cout <<"call A's constructor"<<Endl;}7 Private:8 intDataa;9 };Ten voidMain () One { AA A (2); -}
3.2 However, it is important to note that derived classes cannot directly use the initialization table of a parameter when constructing a base class component
B (intint" call B's constructor " << Endl;} Error!!
3.3 It is not possible to write other statements such as output statements:
B (intint" call B's constructor " << endl{}//Error!!!!)
3.4 It is possible to call the constructor of the base class and the initialization table of the data member at the same time
1#include <iostream>2 using namespacestd;3 classA4 {5 Public:6AintA):d Ataa (a) {cout <<"call A's constructor"<<Endl;}7 Private:8 intDataa;9 };Ten classB: PublicA One { A intDatab; - Public: -BintBintA): A (a), Datab (b) {cout <<"Call B's constructor"<<Endl;} the }; - voidMain () - { -b b (2,5); +}
- B (intint" call B's constructor " << Endl;}
This is the line of code, Datab (b) refers to the initialization list to write, a (a) is the base class constructor, which is very concise.
and the order of the code is independent of the position of Datab (b), which is to initialize a (a) first, then initialize the Datab, and finally execute the function body.
3.5 Such writing is however not possible:
14 B ( int b, int a): A (a) { datab (b); cout << call B's constructor "
B (intint" call B's constructor " << Endl;} Error!!
This is the correct wording:
B (intint" call B's constructor " << Endl;}
The constructor of the "C + + Learning path" derived class (i)