50. Make base class destructors public and virtual, or protected and nonvirtual

Summary

To delete, or not to delete; that is the question: If deletion through a pointer to a base Base should be allowed, then Base’s destructor must be public and virtual. Otherwise, it should be protected and nonvirtual.

Discussion

This simple guideline illustrates a subtle issue and reflects modern uses of inheritance and object-oriented design principles.

For a base class Base, calling code might try to delete derived objects through pointers to Base. If Base’s destructor is public and nonvirtual (the default), it can be accidentally called on a pointer that actually points to a derived object, in which case the behavior of the attempted deletion is undefined. ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.