in C++: Why should the destructor of base classes be virtual?
The better question is when and why. Your question indicates that you think all base classes should have virtual destructors, which is not quite true.
It would make it impossible to apply the empty base class optimization, and could multiply the size of classes up to 16 times than what it would be without virtual
on common platforms.
A virtual
destructor is needed when you delete
an object whose dynamic type is DerivedClass
by a pointer that has type BaseClass*
. The virtual
makes the compiler associate information in the object making it able to execute the derived class destructor. Missing the virtual
in such case causes undefined behavior.
If you don't need this, and your class is only used as a base class, it's best to make the destructor protected
, thus preventing that users accidentally delete
in the described way.