Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a virtual destructor ever be a bad thing?

Tags:

c++

I always mark my classes with a virtual destructor even when it is not needed. Other than maybe a small performance hit could there be a situation where having a virtual destructor when you do not need one cause memory errors or something terrible?

Thanks

like image 378
jmasterx Avatar asked Dec 02 '22 22:12

jmasterx


2 Answers

It’s a fundamental flaw to make all classes extensible. Most classes are simply not suitable to be inherited from and it makes no sense to facilitate this if you don’t design classes for extension up front.

This is just misleading the users of your API who will take this as a hint that the class is meaningfully inheritable. In reality, this is rarely the case and will bring no benefit, or break code in the worst case.

Once you make a class inheritable, you’re settled with it for the rest of your life: you cannot change its interface, and you must never break the (implicit!) semantics it has. Essentially, the class is no longer yours.

On the other hand, inheritance is way overrated anyway. Apart from its use for public interfaces (pure virtual classes), you should generally prefer composition over inheritance.

Another, more fundamental case where a virtual destructor is undesirable is when the code you have requires a POD to work – such as when using it in a union, when interfacing with C code or when performing POD-specific optimisations (only PODs are blittable, meaning they can be copied very efficiently). [Hat tip to Andy]

A word about performance overhead: there are situations in which lots of small objects are created, or objects are created in tight loops. In those cases, the performance overhead of virtual destructors can be a crucial mistake.

Classes which have virtual function tables are also larger than classes without, which can also lead to unnecessary performance impact.

All in all, there are no compelling reasons to make destructors virtual, and some compelling reasons not to.

like image 101
Konrad Rudolph Avatar answered Dec 17 '22 05:12

Konrad Rudolph


There's no point in declaring it virtual if you don't plan on inheriting from the class (or if the class is not meant to be inherited from).
On the other hand, if you want to access this class polymorphically, then yes, virtual destructor is a good thing to have.

But to answer your question precisely, it can not cause any "terrible memory errors" and marking it virtual all the time can't really hurt you.

But i see no reason to use a virtual destructor all the time. It's up to you.

Also, this post by Herb brings some light into the matter.

like image 37
ScarletAmaranth Avatar answered Dec 17 '22 04:12

ScarletAmaranth