Virtual destructor in C++

Virtual destructor in C++

usage: set the destructor to virtual if and only if the class contains more than one virtual function;

  • Making a class's destructor virtual for no reason can affect performance because it adds a virtual function table to the class, doubles the size of the object, and potentially reduces its portability.
  • When a class contains a pure virtual function, the class is an abstract class and has the intention of serving as a base class. If the destructor is not declared as a pure virtual function, it may cause memory leaks.

The problem solved: the pointer of the base class points to the object of the derived class, and the pointer of the base class is used to delete the derived class object
. There must be pure virtual functions in a class.

Application examples

include

#include<iostream>
using namespace std;
class Base
{ 
public: 
Base() { cout <<"contructor Base!"<<endl; };
~Base() { cout<<"destructor Base!"<<endl; }
} 
class Child : public Base 
{ 
public:
 Child() { cout <<"contructor Child!"<<endl; };
 ~Child() { cout <<"destructor Child!"<<endl; }; 
} 
int main()
{
    Base *pBase = new Child();
    delete pBase;
    pBase = null;
    return 0;
}

Running result:
constructor Base!
constructor Child!
destructor Base!

delete pBase only calls the destructor of the base class and does not call the destructor of the subclass, so when the destructor of the base class is not a pure virtual function, it will cause a memory leak.

Usually, the programmer's experience is that when there is a virtual function in the class, the destructor should be written as virtual. Because there is a virtual function in the class, it means that it wants to make the base class pointer or reference point to the derived class object. , at this time, if the constructor of the derived class uses the memory dynamically generated by new, then the data must be deleted in its destructor, but in general programs like the above, this operation only calls the destructor of the base class If it is marked as a virtual destructor, the system will call the destructor of the derived class first, and then call the destructor of the base class itself.

Guess you like

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