Since the derived class contains the base class, when we create a derived class, the system will first create a base class. It should be noted that the derived class will absorb all members of the base class, but does not include the constructor and the destructor mentioned later. This means that when creating a derived class, it will first call the base class before calling its own constructor. Constructor .
Here we can verify this through code:
#include<iostream>usingnamespacestd;classClock{private:intH;intM;intS;public:Clock(){cout<<Clock'sConstructorCalled!<<endl;}};classAlarmClock:publicClock{private:intAH;intAM;public:AlarmClock (){cout<<AlarmClock'sConstructorCalled!<<endl;}};intmain(){AlarmClockA;return0;}
The running screenshot is as follows:
We can see that only one derived class object is defined, and the constructors of the derived class and the base class will be called automatically. The calling order is to call the constructor of the base class first and then the constructor of the derived class .
What you have seen above is the most common and simplest calling method. This is only implicit, that is, it is called automatically without writing it out. So how to call it when the constructor of the base class takes parameters? Is this okay? How to pass parameters?
Answer: Then we need to tell the compiler explicitly, that is, write it out clearly and specify the parameters to pass.
The general writing format is:
Derived class constructor name (total parameter list column): Base class constructor (actual parameter list column)
For example code:
#include<iostream>usingnamespacestd;classClock{private:intH;intM;intS;public:Clock(){cout<<Clock'sConstructorCalled!<<endl;}Clock(inth,intm,ints){this->H=h ;this->M=m;this->S=s;cout<<Clock'sConstructorwithparameterCalled!<<endl;}};classAlarmClock:publicClock{private:intAH;intAM;public:AlarmClock(){cout<<AlarmClock' sConstructorCalled!<<endl;}AlarmClock(inth,intm,ints):Clock(h,m,s){cout<<AlarmClock'sConstructorwithparameterCalled!<<endl;}};intmain(){AlarmClockA(8,10,30 );AlarmClockB;return0;}
Please pay attention to the constructor of the derived class. Later, the colon and the parameters of the base class are passed, and the parameters in the base class are actual parameters to realize the explicit parameter call. Please practice on your computer!
It should be noted that once there is a constructor with parameters in the base class, there must be a derived class constructor with explicit parameter passing in the derived class to realize the transfer of parameters in the base class and complete the initialization work.