Like constructors, destructors cannot be inherited.
When you create a derived class object, the constructor's invocation order is the same as the inheritance order, the base class constructor is executed, and then the constructor of the derived class is executed. For destructors, however, the invocation order is reversed, that is, the destructor of the derived class is executed first, and then the destructor of the base class is executed.
Take a look at the following example:
#include <iostream>
using namespace std;
Class a{public
:
A () {cout<< "a constructor" <<ENDL;}
~a () {cout<< "A destructor" <<ENDL;}
;
Class B:public a{public
:
B () {cout<< "B constructor" <<endl;}
~b () {cout<< "B destructor" <<ENDL;}
;
Class C:public b{public
:
C () {cout<< "C constructor" <<endl;}
~c () {cout<< "C destructor" <<ENDL;}
;
int main () {
C test;
return 0;
}
Run Result:
A constructor
b constructor
c constructor
C destructor
b destructor
a destructor
From the results of the run, it is clear that the execution order of constructors and destructors is reversed.
It should be noted that a class can have only one destructor, which does not have two semantics when invoked, so the destructor does not need to be called explicitly.