The necessity of c++ virtual destructor

    We know that when developing with C++, the destructor of the class used as the base class is generally a virtual function.

But why do it? Here is a small example to illustrate: 

  

 1 #include<iostream>
 2 using namespace std;
 3 class Base
 4 {
 5 public:
 6     Base() {}
 7     virtual ~Base();
 8 };
 9 
10 class Subclass :public Base
11 {
12 public:
13     Subclass() {}
14     ~Subclass();
15 };
16 Base::~Base()
17 {
18     cout << "Base destructor is called." << endl;
19 }
20 
21 Subclass::~Subclass()
22 {
23     cout << "Subclass destructor is called." << endl;
24 }
25 
26 int main()
27 {
28     Base *b = new Subclass;
29     delete b;
30     return 0;
31 }

Output result:   

Subclass destructor is called.
Base destructor is called.

This is very simple and very easy to understand.
However, if you remove the virtual before the class Base destructor, the output will look like this:

Base destructor is called.

That is, the destructor of class Base is not called at all! Under normal circumstances, the destructor of a class releases memory resources, and if the destructor is not called, it will cause memory leaks. I think all C++ programmers know the dangers of this. Of course, all your efforts will be in vain if other work is done in the destructor.
    So, the answer to the question at the beginning of the article is -- this is done so that when an object of a derived class is deleted with a base class pointer, the derived class's destructor will be called.
    Of course, it is not necessary to write the destructors of all classes as virtual functions. Because when there are virtual functions in the class, the compiler will add a virtual function table to the class to store the virtual function pointer, which will increase the storage space of the class. So, only when a class is used as a base class, write the destructor as a virtual function.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324642924&siteId=291194637