Effective C++: discouraging protected inheritance?

前端 未结 5 706
北恋
北恋 2021-02-02 11:10

I was reading Scott Meyers\' Effective C++ (third edition), and in a paragraph in Item 32: Make sure public inheritance is \"is-a\" on page 151 he make

5条回答
  •  眼角桃花
    2021-02-02 11:36

    I don't know if Meyers is advising us to refrain from using protected inheritance, but it seems you should avoid it if Meyers is on your team, because at least he won't be able to understand your code.

    Unless your co-workers know C++ better than he does, you should probably also stay away from protected inheritance. Everybody will understand the alternative, i.e. using composition.

    I can imagine however a case where it could make sense: You need access to a protected member in a class whose code you can't change but you don't want to expose an IS-A relationship.

    class A {
    protected:
      void f(); // <- I want to use this from B!
    };
    
    class B : protected A {
    private:
      void g() { f(); }
    };
    

    Even in that case, I would still consider making a wrapper with public inheritance that exposes the protected base members with public methods, then compose with these wrappers.

    /*! Careful: exposes A::f, which wasn't meant to be public by its authors */
    class AWithF: public A {
    public:
      void f() { A::f(); }
    };
    
    class B {
    private:
      AWithF m_a;
      void g() { m_a.f(); }
    };
    

提交回复
热议问题