34. Prefer composition to inheritance. Summary Inheritance is the second-tightest coupling relationship in C++, second only to friendship. Tight coupling is undesirable and should be avoided where possible. Therefore, prefer composition to inheritance unless you know that the latter truly benefits your design. ... Exceptions Do use public inheritance to model substitutability. (See Item 37.) Even if you don't need to provide a substitutability relationship to all callers, you do need nonpublic inheritance if you need any of the following ... : • If you need to override a virtual function. • If you need access to a protected member. • If you need to construct the used object before, or destroy it after, a base class. • If you need to worry about virtual base classes. • If you know you benefit from the empty base class optimization ... • If you need controlled polymorphism. ... substitutability relationship should be visible only to selected code ... |
virtual
.