c++ – Virtual destructor

Question:

There was a question about the virtual destructor.

As far as I understand, a virtual destructor is needed so that in the inherited class that we have (from the base one) it is possible to call (directly from there) the destructor of the base one. a simple destructor of an inherited class does not understand, then you need to create a virtual one.

And all this so that there is no memory leak.

Did I get the point?

Answer:

No, not a bit like that. The destructor of the base class from the destructor of the derivative does not need to be called (and it cannot be called), it will be called automatically itself. The problem is different: the destructor of the derived class may not be called!

Imagine this situation:

class Person
{
    ~Person() { } // деструктор не виртуальный
};

class Spy : public Person
{
    Gadget* gadgets;
public:
    Spy() { gadgets = new Gadget[10]; }
    ~Spy() { delete[] gadgets; }
};

std::vector<Person*> citizens;
// наполнить значениями
for (Person* citizen : citizens)
    delete citizen;

What happens if there is one Spy on the list? And here's what: when an object of type Spy destroyed by a pointer of type Person* , the non-virtual destructor ~Person called. This means that the memory for the gadgets array will not be freed. So much for the memory leak.

In fact, besides a memory leak, any other nuisance can occur, because the destructor you were counting on will not be called! For example, the file may not close, and the next time you try to open it, the program will crash. Or the mutex will not be released, and when trying to get it, the program will hang. Well, a bunch of all sorts of disasters can happen.

Worse, according to the standard, the absence of a virtual destructor in this case is an undefined behavior, that is, the program has the right to do anything: format the hard drive, confess its love to your chemist through Vkontakte, or add valerian drinks to a bowl of Whiskas.


Yes, and in C there are no destructors at all.

Scroll to Top