1. Call relationship of default constructor
The following example shows the call sequence between the base class and the derived constructor. Create a base class and then a derived class. When the object is destroyed, the derived class is first followed by the base class.
#include
<iostream>#include
<string>using namespace
std;class
CBase { string name; int
age;public
: CBase() { cout <<"BASE" << endl; } ~CBase() { cout <<"~BASE" << endl; }};class
CDerive : public
CBase {public
: CDerive() { cout <<"DERIVE" << endl; } ~CDerive() { cout <<"~DERIVE" << endl; }};int
main ( ) { CDerive d; return
0;}
Ii. parameter transfer
When a parameter exists, the parameter must be transmitted to the base class. Note the methods passed in the example (8th rows and 19th rows ).
#include
<Iostream>#include
<String>using namespace
STD;class
Cbase {string name;public
: Cbase (string S): Name (s) {cout <"Base :"<Name <Endl ;}~ Cbase () {cout <"~ Base"<Endl ;}};class
Cderive:public
Cbase {int
Age;public
: Cderive (string s,int
A): cbase (s), age (a) {cout <"Derive :"<Age <Endl ;}~ Cderive () {cout <"~ Derive"<Endl ;}};int
Main () {cderive D ("Xiaoya", 27 );return
0 ;}
3. parameter transfer for three generations of grandparents
When there are three layers of inheritance, parameters must be passed one by one (30th rows, 19th rows, 8th rows ).
#include
<Iostream>#include
<String>using namespace
STD;class
Cbase {string name;public
: Cbase (string S): Name (s) {cout <"Base :"<Name <Endl ;}~ Cbase () {cout <"~ Base"<Endl ;}};class
Cderive:public
Cbase {int
Age;public
: Cderive (string s,int
A): cbase (s), age (a) {cout <"Derive :"<Age <Endl ;}~ Cderive () {cout <"~ Derive"<Endl ;}};class
Cson:public
Cderive {string ID;public
: Cson (string S1,int
A, string S2): cderive (S1, A), ID (S2) {cout <"Son :"<Id <Endl ;}~ Cson () {cout <"~ Son"<Endl ;}};int
Main () {cson S ("Xiaoya", 27,"8503026");return
0 ;}
Constructors of base classes and derived classes