Confusion with copy constructor and private member

前端 未结 3 400
猫巷女王i
猫巷女王i 2021-01-25 15:51

Suppose I have the following class:

class Test
{
             int num;
     public:
             Test(int x):num(x){}
             Test(const Test &rhs):num(         


        
相关标签:
3条回答
  • 2021-01-25 16:26

    Access limitations are per-class, not per-object.

    "private" means -- can only be accessed from within the same class.

    "protected" means -- can be accessed from within the same class, and can also be accessed from within derived-classes (in derived classes, protected non-static members can only be accessed through variables with derived class type).

    "public" means -- can be accessed by anything.

    The point of access limitations is to limit the region of code that has to be inspected in order to understand where the values are used, rather than to stop code from using the values.

    0 讨论(0)
  • 2021-01-25 16:28

    Private members are private to the class itself, not the instances of the class.

    0 讨论(0)
  • 2021-01-25 16:32

    private doesn't mean private to the object instance. It means private to that class. An instance of a class T can access private members of other instances T. Similarly, a static method in a class T can access private members of instances of T.

    If private restricted access to only the individual instance, it would make objects non-copyable, since as you pointed out, the copy constructor would not be able to read data from the original instance.

    0 讨论(0)
提交回复
热议问题