A brief introduction to the destructor of derived classes in C++ programming

  • 2020-05-05 11:35:16
  • OfStack

Like constructors, destructors cannot be inherited.

When a derived class object is created, the constructor is called in the same order as the inheritance order, with the base class constructor executed first and then the constructor of the derived class. With destructors, however, the call order is reversed: the destructor of the derived class is executed first, followed by the destructor of the base class.

See 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;
}

Result:


A constructor
B constructor
C constructor
C destructor
B destructor
A destructor

It is clear from the results that the constructor and destructor execute in opposite order.

It is important to note that a class can only have one destructor and there is no ambiguity when called, so destructors do not need to be explicitly called.


Related articles: