23

I have the following code:

class A 
{
private:
    int x;
public:
    A()
    {
        x = 90;
    }
    A(A a1, A a2)
    {
        a1.x = 10;
        a2.x = 20;
    }
    int getX()
    {
        return this->x;
    }
};

I know that code might be weird but I don't understand why a1 and a2 can access private data member x?

ipkiss
  • 13,311
  • 33
  • 88
  • 123

4 Answers4

30

Good question. The point is that protection in C++ is class level, not object level. So a method being invoked on one object can access private members of any other instance of the same class.

This makes sense if you see the role of protection being to allow encapsulation to ensure that the writer of a class can build a cohesive class, and not have to protect against external code modifying object contents.

Another thought as to the real "why?". Consider how you write almost any copy constructor; you want access to the original's underlying data structure, not its presented interface.

Keith
  • 6,756
  • 19
  • 23
  • `private` works purely at class level. `protected` [doesn't](http://stackoverflow.com/questions/3247671/accessing-protected-members-in-a-derived-class-c) – MSalters Sep 13 '11 at 08:38
  • @MSalters: Sure it does. Members of a class still get enhanced access to other objects of that class type, including the ability to access protected members within base subobjects (of other objects of the class type where the code is). – Ben Voigt Jun 01 '13 at 03:28
  • Access specifiers in c++ regulate access to _names_, not objects. It's actually possible to access private members of different classes if you can find a legal way to refer to them. – bames53 Sep 12 '13 at 03:15
4

Any member function of the class as well as the constructors can access the private data. That is the private members of the instance object the method is called on or the private members of other instances.

In this case it's the constructor and it's other instances (namely a1, a2).

Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
0

Short answer: In member methods of class A, all the members of (object/pointer and static member) class A can be accessed.

iammilind
  • 68,093
  • 33
  • 169
  • 336
0
A(A a1, A a2)
{
    a1.x = 10;
    a2.x = 20;
}

Now from my understanding, you question is how can a object that invoked the constructor call can access other class member variables ?

Now, both the constructor and the arguments a1,a2 are class scoped. So, it can access all it's members irrespective of it's access level. This too will also work in the constructor -

this->x = a1.x; // Notice that "this" members can be accessed too.
                // How ever both the member variables are different and are part of
                // different objects.
Mahesh
  • 34,573
  • 20
  • 89
  • 115