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.

4
  • 6
    How would you implement a copy constructor if objects of the same class could not access each other's private members? Commented Jan 29, 2016 at 17:20
  • 1
    Tony D explained the design rationale in the thread you mention Commented Jan 29, 2016 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. Commented Jan 29, 2016 at 17:52
  • @djf you're right thanks I must read Tony D explanation Commented Jan 29, 2016 at 18:01

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Your first paragraph hits the nail on the head.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.