38. Practice safe overriding

Summary

Override responsibly: When overriding a virtual function, preserve substitutability; in particular, observe the function’s pre- and post-conditions in the base class. Don’t change default arguments of virtual functions. Prefer explicitly redeclaring overrides as virtual. Beware of hiding overloads in the base class.

Discussion

Although derived classes usually add more state (i.e., data members), they model subsets, not supersets, of their base classes. In correct inheritance, a derived class models a special case of a more general base concept (see Item 37).

This has direct consequences for correct overriding: Respecting the inclusion relationship implies substitutability—operations that apply to entire ...

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.