TransWikia.com

Why is it not the case that all d-tors of virtual C++ classes be virtual?

Software Engineering Asked on October 29, 2021

I am basically plagiarizing When NOT to use virtual destructors?. The excellent answers remind us that C++ is pay only for what you use.

However, the Standard is a couple of thousand pages long. The d-tor of a class containg at least one virtual method is implicitly virtual. wouldn’t have loaded it too much.

Why do we need to keep the cognitive burden of doing it, to teach newbies to do it, to sometimes forget and thus create horrible bugs?

I hope the question has an objective answer – the language spec has been deliberated for some time now.

One Answer

As you rightly point out, C++ obeys the language design principle of "pay only for what you use".

Making the destructor virtual when there is at least one virtual method is a rule of thumb, and nothing more:

  • There are plenty of cases where you can have a class with a virtual function without needing a virtual destructor.
  • Conversely, there are as many cases where you need a virtual destructor even when you don't have any other virtual function.

Bjarne Stroustrup explained the need for virtual destructors in his book The Design and evolution of C++ (page 216):

The use of a virtual destructor is crucial for getting destruction right in cases in which a user deletes an object of a derived class through a pointer of the base class.

Why? Because in this exact scenario, without virtual destructor, it would be the destructor of the base class that would be called, and this could miss a lot of resources to be freed in the derived class.

So the real need for virtual destructor is not at all the existance of a virtual function. This known rule of thumb/guideline is there, only because: when you have at least one virtual function, it is very probably because you want polymorphism and access objects of derived classes through pointers of the base class. And if you do this, there's also a higher probability that you delete some of these objects via their base pointers.

If the language specifications should provide for a rule to automatically define when a destructor has to be virtual, it would certainly not be the simple sentence that you propose, but dozen of pages to cover all the tricky special cases. And since nobody would be sure that it's fully accurate.... Wait! Isn't that what happened? ;-)

Answered by Christophe on October 29, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP