Object-oriented – C++ Virtual destructors used only when there are virtual functions

cconstructorsdesignobject-oriented

This is from Effective C++ (Meyers):

Classes not designed to be base classes or not designed to be used polymorphically should not declare virtual destructors

I don't understand why non-polymorphic classes should not declare virtual destructors.

Assuming I have a parent class and a child class, with no virtual functions, and I have a parent-class-pointer to a child object: if I call delete on the parent-class-pointer, it will only call the parent destructor, even though I also want to call the child destructor.

Best Answer

The keyword here is not designed

Classes not designed to be base classes or not designed to be used polymorphically

Virtual functions/destructors are not free: they cause performance overhead so you may not want to use them in all cases. However, deleting a derived class object using a pointer to a base class that has a non-virtual destructor results in undefined behavior:

http://www.geeksforgeeks.org/g-fact-37/

So that's the trade off between performance and safety.