Inheritance lets a subclass derive state and behavior from a superclass. The subclass can add its own members or override inherited behavior. In C++, public members form the interface, private members remain restricted to the defining class, and protected members are available to subclass member functions. section 1.8
Use inheritance to model an is-a relationship: a TrainSet is a Toy, and Fiction, Cookbook, and Howto are Books. A UML generalization arrow points from the subclass toward the superclass. section 4.4.3 section 7.3
Check an inheritance design for these practical risks:
- Watch for duplicated behavior across subclasses; repeated play or sound implementations violate Don't Repeat Yourself and become harder to maintain as the hierarchy grows. section 7.3
- Question hardcoded behavior in each subclass; inheritance fixes the type structure but does not necessarily make behavior flexible. section 7.3
- Compare inheritance with composition or aggregation when behavior varies independently. Template Method keeps an algorithm outline in a superclass, while Strategy makes whole algorithms interchangeable through composition. section 8.3 section 8.4
Toy behaviors: from fixed subclasses to configurable objects
A first Toy hierarchy gives ToyCar, ModelAirplane, and TrainSet separate play() and sound() overrides. ToyCar and TrainSet duplicate rolling behavior, while ToyCar and ModelAirplane duplicate engine sounds. Refactoring PlayAction and Sound into polymorphic behavior classes lets Toy receive behaviors at construction time and change them later with set_play() or set_sound(). The result retains the Toy is-a hierarchy while using has-a relationships for shared, replaceable behavior. section 7.3
Figure 4.11 Superclass Book has subclasses Fiction, Cookbook, and Howto. Also, superclass Attributes has subclasses FictionAttrs, CookbookAttrs, and HowtoAttrs. This figure shows two ways of drawing generalization diagrams.
Use the UML figure to compare superclass–subclass generalization in the Book and Attributes hierarchies. section 4.4.3


















