c++: access private members in the copy constructor

considering the following code:


class Test
{
int num;
public:
Test(int x):num(x){}
Test(const Test &rhs):num(rhs.num+1){}
};
int main()
{
Test test(10);
Test copy = test;
}

The num in the copy should be 11, and my question is about inside the copy constructor, why can we access the private member num of test using num to initialize the num in the copy?

explanations:
private members are private to the class itself, not the instances of the class.
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.

c++: access private members in the copy constructor》有1个想法

发表评论

邮箱地址不会被公开。 必填项已用*标注