how can private data be accessed in copy CTOR

The following code is weird, the reason is that private data can be accessed here! but it really can be compiled sucessfully, am I crazy or is it mad?!

1
2
3
4
5
6
7
class A
{
public:
    A(const A &a):size(a.size) {}
private:
    int size;
};
Last edited on
The private data is being accessed by the class itself, which is allowed. Private means that only the class is able to change the data.
Neither. You're ignorant. Luckily, it can be cured.

Private members can be accessed only by the class itself. The parameter is an A, so, logically, the copy constructor of A can access its members.

The class can always access all members of all its instances (as long as they're passed as parameters, obviously). The only exception is protected private members in base classes.
Last edited on
The input to the copy constructor and assignment operator (rhs params) are const references so there is no risk to data being changed in the rhs. I have had brain farts about that occasionally but it makes sense to allow this otherwise you'd be forced to write accessors for every single attribute just to implement a copy constructor and assignment operator.
Topic archived. No new replies allowed.