Do Sub-Classes Really Inherit Private Member Variables?

前端 未结 7 931
醉酒成梦
醉酒成梦 2020-12-07 23:58

Basically as far as I know, when you create a base class with a public, protected, and private section and variables/functions in each the public and protected sections will

7条回答
  •  有刺的猬
    2020-12-08 00:09

    "When you create a sub-class you never receive anything from the private section of the [base class]. If this is true then an object of the sub-class should never have it's own version of a private variable or function from the base class, correct?"

    No. The derived class inherits all the members of the base class, including the private ones. An object of the inherited class has those private members, but does not have direct access to them. It has access to public members of the base class that may have access to those members, but it (the derived class) may not have new member functions with such access:

    class yourClass : public myClass
    {
    public:
      void playByTheRules()
      {
        setMyVariable(); // perfectly legal, since setMyVariable() is public
      }
    
      void tamperWithMyVariable()
      {
        myVariable = 20; // this is illegal and will cause a compile-time error
      }
    };
    

提交回复
热议问题