Exceptions
Team LiB
Previous Section Next Section

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, in rough order from most common (the first two points) to exceedingly rare (the rest):

  • 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, including that it matters in this case and that your target compiler(s) actually perform it in this case. (See Item 8)

  • If you need controlled polymorphism. That is, if you need a substitutability relationship, but that relationship should be visible only to selected code (via friendship).

    Team LiB
    Previous Section Next Section