Inheriting private members in C++

前端 未结 7 1956
不知归路
不知归路 2020-12-02 23:59

suppose a class has private data members but the setters and getters are in public scope. If you inherit from this class, you can still call those setters and getters -- ena

7条回答
  •  伪装坚强ぢ
    2020-12-03 00:24

    Using the pattern

    class MyClass {
      private: int a;
      public: void setA(int x) { a = x; }
      public: int getA() const { return a; }
    };
    

    seems object-orientated and has the sent of encapsulation.

    However as you noticed, you can still directly access the private field and there is nothing gained over just making a public and accessing it directly.

    Using getters and setters like this does not really make sense in C++.

提交回复
热议问题