3

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.

Community
  • 1
  • 1
segevara
  • 610
  • 1
  • 7
  • 18
  • 6
    How would you implement a copy constructor if objects of the same class could not access each other's private members? – Archimaredes Jan 29 '16 at 17:20
  • 1
    [Tony D explained the design rationale](http://stackoverflow.com/a/17721201/961781) in the thread you mention – djf Jan 29 '16 at 17:23
  • @Archimaredes I think it possible e.g. I can just add getter method for every private variable but yes I agree it will make impossible automatic generation of copy constructor etc. – segevara Jan 29 '16 at 17:52
  • @djf you're right thanks I must read Tony D explanation – segevara Jan 29 '16 at 18:01

2 Answers2

3

You could easily work around such object-level protections, so I doubt they would be worth the effort. That is, replace

void f(A &a) {
    a.c = 2;
}

with

void f(A &a) {
    a.update_c(2);
}
void update_c(int val) {
    c = val;
}
chepner
  • 497,756
  • 71
  • 530
  • 681
3

The access modifiers work on class level, and not on object level.

The reason for this is because the compiler doesn't actually know about any specific object instances. At compile time, the compiler only has knowledge of the class structure that will be used, not the specific instances of that class structure in memory at run time.

The public/private/protected access controls are a feature to help architects govern how their code is used by other programmers. Since this is a coding only paradigm, it has little to no impact on the run time code. The code generated by the compiler has nothing resembling these access controls at all.

So in short, the reason this feature works this way is because it is only intended to be an aid to the software architect.

acid1789
  • 139
  • 4