When to use a virtual destructor
Class Base
{
Public:
Base ();
~ Base ();
...
};
Class Derived: public Base
{
...
};
Base * p = new Derived;
Delete p;
In this example, if the base class pointer p points to the object of the derived class, releasing the object of the derived class through the base class pointer will cause resource leakage. Because the destructor of the base class are not virtual, delete p will only call the destructor of the base class, And the destructor of the derived class will not be called. The solution is to change the destructor of the base class to a virtual destructor.
So when should I use a virtual destructor? As long as any class has a built-in Bual function, this means that the class is designed as a base class for Polymorphism purposes. Basically, this class should also have a virtual destructor. If a class does not contain virtual functions, it usually indicates that it is designed not to be used as a multi-state base class. It is difficult to make the Destructor virtual when the class is not treated as a base class or is not used as a polymorphism. Because a class has a virtual function, the class object will add a virtual table pointer (virtual table pointer) to decide which virtual function should be called during running.
In addition, the Destructor can also be pure virtual destructor. A pure virtual function represents an abstract class. If a class does not have any member function and you want to design it as an abstract class, you can only use the Destructor as a pure virtual function. For example:
Class Test
{
Public:
Virtual ~ Test () = 0;
}
// Virtual destructor Definition
Virtual ~ Test ()
{
}
Generally, the pure virtual function does not need to be defined, but there is an exception here. The pure virtual destructor must provide the implementation body to compile the link. The order of the Destructor is that the destructor of the deepest derived class is called first, and then the destructor of each layer is called in turn. Therefore, the compiler will create a pair in the destructor of the derived class of the Test class ~ Test (), so you must provide the definition of this destructor.
Author: tbw