1

I was surprised to discover that this compiles.

class A
{
    int i;
public:
    A() {}
    A(A &a) {i = a.i;}
};

int main(void)
{
    A a1;
    A a2(a1);
}

That is, the object a2 has access to the private members of the object a1. Why is this the case i.e. why is this useful? How can this access be restricted, if needed?

Vorac
  • 8,726
  • 11
  • 58
  • 101
  • 4
    This is *exactly* what `private` does – Paolo M Jan 08 '16 at 09:53
  • 4
    What a curious question. I hope it generates interesting responses. – ApproachingDarknessFish Jan 08 '16 at 09:55
  • 2
    Those modifiers restrict access on classes, not instances. That's simply how they work. – Jaa-c Jan 08 '16 at 09:59
  • Bear in mind that, since you are the one creating the class, you are the one controlling how it is used. No one is making you access the other instance's members, so what use would this protection be? – BoBTFish Jan 08 '16 at 10:00
  • 3
    For example, if access control were per-instance, implementing a copy constructor would require every single member variable to have a public getter. – molbdnilo Jan 08 '16 at 10:11
  • Also, consider `class A { int i; public: void foo(A& a) { a.i = 0; } }; int main() { A b; b.foo(b); }`. If `b.foo(b);` should succeed (`b` is accessing its own private member) then access control must be performed at runtime. – molbdnilo Jan 08 '16 at 10:20

0 Answers0