C++ - when to use public, protected, private inheritance

See also: Zuga.net - C++ - public vs. protected vs. private inheritance

public inheritance models an is-a relationship.

  class CDog : public CMammal { };
  

A dog is a mammal.

  • Use public to inherit base class implementation and interface. Public members of the base (it's interface) are public in the derived.
  • A derived class object can be used anywhere a base class object is expected (because derived is a base).

protected inheritance models an is-implemented-using relationship.

  class CCar : protected CAccelerator, protected CBrake, protected CClutch { };
  

A car is implemented using an accelerator, a brake, a clutch, etc., and we DO want to expose these subcomponents to subclasses of car.

  • Use protected to inherit base class implementation only. Public members of the base (it's interface) become protected in the derived.
  • Protected inheritance exposes implementation to subclasses of derived.

private inheritance models an is-implemented-using relationship.

  class CCar : private CAccelerator, private CBrake, private CClutch { };
  

A car is implemented using an accelerator, a brake, a clutch, etc., and we DON'T want to expose these subcomponents to subclasses of car.

  • Use private to inherit base class implementation only. Public members of the base (it's interface) become private in the derived.
  • Private inheritance hides implementation from subclasses of dervied.

Ads by Google



Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath