I'm trying to understand why the object of the same class can access private member of each other. Actually I know that
The access modifiers work on class level, and not on object level.
From here. But I don't understand reasons of it. I only can suppose that it connected with automatic generation of copy constructor and copy assignment operator (which obviously should have access to private data to copy it) but I'm not sure. Actually it looks weird that any different instance of one class can change private variables of each other e.g.:
#include <iostream>
class A{
int c;
public:
A():c(1){}
void f(A & a){
a.c = 2;
}
int getC(){return c;}
};
int main()
{
A a1;
A a2;
a1.f(a2);
std::cout << "A1 c " << a1.getC() << std::endl;
std::cout << "A2 c " << a2.getC() << std::endl;
return 0;
}
a1 will change a2.c and output will be
A1 c 1
A2 c 2
Thanks.