Difference between private, public, and protected inheritance

后端 未结 16 1768
灰色年华
灰色年华 2020-11-21 06:15

What is the difference between public, private, and protected inheritance in C++?

16条回答
  •  广开言路
    2020-11-21 06:54

    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.

提交回复
热议问题