Like the previous section, in a derived class, the destructor cannot be absorbed by the derived class.
The key point is that everyone needs to be clear about the calling order of destructors of derived classes and base classes. The calling order of destructors is completely opposite to that of constructors. We can output a message in the derived class destructor and base class destructor and observe Calling sequence:
/************************************//Des: C++ tutorial demo//Author: Huang//Copyright:www.dotcpp.com//Date:2017/11/15********************************** *******/#include<iostream>usingnamespacestd;classClock{private:intH;intM;intS;public:Clock(){cout<<Clock'sConstructorCalled!<<endl;}~Clock(){cout< <Clock'sDestructorCalled!<<endl;}};classAlarmClock:publicClock{private:intAH;intAM;public:AlarmClock(){cout<<AlarmClock'sConstructorCalled!<<endl;}~AlarmClock(){cout<<AlarmClock' sDestructorCalled!<<endl;}};intmain(){AlarmClockA;return0;}
Running screenshot:
As you can see, defining a derived class AlarmClock will generate the base class first, while the destruction order is reversed.
Constructor calling sequence: base class -> derived class
Destructor calling sequence: derived class -> base class
Please try it yourself.