Item 7: Declare Destructors Virtual in Polymorphic Base Classes
On the other hand, classes not designed to be base class or be used polymorphically should not declare destructor virtual.
- Virtual function incur costs (space and speed) and so don’t declare destructor virtual when you don’t need to.
- Not all base classes need a virtual destructor, e.g., the
Uncopyable
from previous item doesn’t need it (because they are not intended to be used polymorphically).
- Not all base classes need a virtual destructor, e.g., the
- Aside, don’t inherit a class that is not designed for inheritance.
- Unfortunately C++ doesn’t have
final class
as Java so we can’t disallow that. - You might accidentally “slice” it and cause trouble; see example below.
- Unfortunately C++ doesn’t have
- What if you want to define an abstract class without virtual functions?
Answer: Define a pure virtual destructor (that’s right, not simply declare, but define it).
- Any class with a pure virtual function is an abstract class.
- An abstract class cannot be instantiated.