Do Sub-Classes Really Inherit Private Member Variables?

前端 未结 7 976
醉酒成梦
醉酒成梦 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:19

    myObject and yourObject are two different objects! Why should they share anything?

    Think about it that way: Forget about inheritance and suppose you have a class Person with private int age; and public void setAge (int age) {...}. You then instantiate two objects:

    Person bob;
    Person bill;
    bob.setAge(35);
    

    Would you expect Bill to be 35 now, too? You wouldn't, right? Similarly, your myObject doesn't share its data with yourObject.


    In response to your comment:

    The class yourClass inherits from myClass. That means that both yourObject and myObject have their own myVariable, the latter obviously by definition, the former inherited from myClass.

提交回复
热议问题