C++ virtual destructor details and example code

  • 2020-05-19 05:19:16
  • OfStack

Virtual destructor of C++

I am going to review all the knowledge points once recently. Let's start from the basics and write an inheritance and destruct in a few minutes.

The parent class is A, and the subclass is B. The code is as follows:


class A
{
 public:
 A()
 {
   cout << " structure A"<< endl; 
 }
 ~A()
 {
  cout << " destructor A" << endl;
  }
}
class B:public A
{
 public:
 B()
 {
 cout << " structure B"<< endl; 
 }
 ~B()
 {
 cout << " destructor B"<< endl;
 }

}

At this point in the main function,

Define 1 A object, A a; The output of the run is: construct A destructor A.

Define 1 B object, B b; The output of the run is: construct B to destruct B.

Define a pointer to A that points to B. A *P = new b; The output is: construct A construct B. At this point, many people are prone to problems. Why not call destructor? The object out of new is not deleted, and there is also 1 line of code delete p; The output of the run at this time is: construct A construct B destruct A. This time, we need to use the concept of virtual destructor. Virtual destructor's function: the destructor of the parent class is written as virtual destructor. When deleting the pointer of the parent class, we can delete the object of the subclass to avoid memory leak.

This is done by adding an virtual to line 8 above. The output is: construct A construct B destructor B destructor A. Notice that you can also see the order of calls here, which is the construction of the parent class first, and then the construction of the subclass. The subclass is destructed first, and the parent is destructed last.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: