virtual
- Methods can be virtual or non-virtual
- Constructors cannot be virtual
- What about destructors?
Problem
- When using a Base pointer with a Derived object, the Derived destructor is not called
- Not calling the destructor means that any destructor cleanup is not performed, e.g., RAII
- Not only is the Derived destructor not called, destructors for all fields/data members are also not called
- Why? The compiler uses static dispatch to set up a call to the destructor
- Solution: virtual destructor
Virtual Destructor Classes
Conclusion
- Any base class with a virtual method should have a virtual destructor
- If there is nothing to do in the destructor, use the
default
function specifier
- Default destructors are compiler generated and can be more efficient than user-created destructors
- Prefer to declare a default destructor in the include file, but if an issue, you can declare it in the implementation file, e.g.,
Base::~Base() = default;