C++ why use public, private or protected inheritance?

Tim picture Tim · Jan 19, 2013 · Viewed 11.1k times · Source

Well there is enough information about this subject. For example this thread was very clear to me: Difference between private, public, and protected inheritance

Except one point; Why is it useful?

Answer

TemplateRex picture TemplateRex · Jan 19, 2013

Use public inheritance to reflect an is-a relationship. This is the main use for inheritance, especially in combination with virtual functions. It allows re-use of interface, not just of old code by new code, but also re-use of new code by old code! (because of virtual function dispatch at runtime).

In exceptional circumstances, use private inheritance to reflect an is-implemented-in-terms-of relationship. This is a commonly overused pattern, often the equivalent goal can be reached through composition (having the would-be base class as a data member). Another drawback is that you can easily have multiple inheritance of the same base class (twice or more removed) leading to the so-called Diamond Problem.

Avoid using protected inheritance, it suggest that your class interface is client-dependent (derived classes versus the world). Often this is due to classes having multiple responsiblities, suggesting a refactoring into separate classes is appropriate.