The function of virtual destructor in C++ is analyzed

  • 2020-04-02 01:00:39
  • OfStack

We know, When developed in C++, destructors of classes used as base classes are usually virtual functions. But why? Here's a small example:      
There are the following two classes:

class ClxBase
{
public:
    ClxBase() {};
    virtual ~ClxBase() {};
    virtual void DoSomething() { cout << "Do something in class ClxBase!" << endl; };
};
class ClxDerived : public ClxBase
{
public:
    ClxDerived() {};
    ~ClxDerived() { cout << "Output from the destructor of class ClxDerived!" << endl; }; 
    void DoSomething() { cout << "Do something in class ClxDerived!" << endl; };
};

code

ClxBase *pTest = new ClxDerived;
pTest->DoSomething();
delete pTest;

The output result is:
Do something in class ClxDerived!
Output from the destructor of class ClxDerived!
This is very simple, very easy to understand.
However, if you remove the virtual before the ClxBase destructor, the output will look like this:
Do something in class ClxDerived!
That is, the ClxDerived destructors are not called at all! In general, the destructor of a class is to release memory resources, and the destructor is not called will cause a memory leak. I think all C++ programmers know the danger. Of course, if you do anything else in the destructor, all your efforts are in vain.

So, the answer to the question at the beginning of this article is to do this so that when an object of a derived class is deleted with a pointer to a base class, the destructor of the derived class is called.

Of course, it is not necessary to write all destructors of classes as virtual functions. Because when a class has virtual functions, the compiler adds a table of virtual functions to the class to hold virtual function Pointers, which increases the storage space of the class. Therefore, destructors are written as virtual functions only when a class is used as a base class.

Related articles: