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 namespaceSTD;classCbase {string name;public: Cbase (string S): Name (s) {cout <"Base :"<Name <Endl ;}~ Cbase () {cout <"~ Base"<Endl ;}};classCderive:publicCbase {intAge;public: Cderive (string s,intA): cbase (s), age (a) {cout <"Derive :"<Age <Endl ;}~ Cderive () {cout <"~ Derive"<Endl ;}};intMain () {cderive D ("Xiaoya", 27 );return0 ;}
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 namespaceSTD;classCbase {string name;public: Cbase (string S): Name (s) {cout <"Base :"<Name <Endl ;}~ Cbase () {cout <"~ Base"<Endl ;}};classCderive:publicCbase {intAge;public: Cderive (string s,intA): cbase (s), age (a) {cout <"Derive :"<Age <Endl ;}~ Cderive () {cout <"~ Derive"<Endl ;}};classCson:publicCderive {string ID;public: Cson (string S1,intA, string S2): cderive (S1, A), ID (S2) {cout <"Son :"<Id <Endl ;}~ Cson () {cout <"~ Son"<Endl ;}};intMain () {cson S ("Xiaoya", 27,"8503026");return0 ;}
Constructors of base classes and derived classes