What is the difference between
public
,private
, andprotected
inheritance in C++?
Public inheritance models an IS-A relationship. With
class B {};
class D : public B {};
every D
is a B
.
Private inheritance models an IS-IMPLEMENTED-USING relationship (or whatever that's called). With
class B {};
class D : private B {};
a D
is not a B
, but every D
uses its B
in its implementation. Private inheritance can always be eliminated by using containment instead:
class B {};
class D {
private:
B b_;
};
This D
, too, can be implemented using B
, in this case using its b_
. Containment is a less tight coupling between types than inheritance, so in general it should be preferred. Sometimes using containment instead of private inheritance is not as convenient as private inheritance. Often that's a lame excuse for being lazy.
I don't think anyone knows what protected
inheritance models. At least I haven't seen any convincing explanation yet.