Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With a private modifier, why can the member in other objects be accessed directly?

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?

like image 326
ipkiss Avatar asked Sep 13 '11 04:09

ipkiss


People also ask

Who can access class member with private modifier?

The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

Can objects access private members?

That makes the difference to whether the access is "by the object". Unless main() is the name of a function of 'Car' I don't understand why you think it's attempt at accessing the width variable qualifies in the statement, "...private members could be accessed by the object of the class to which they belong."

Can two objects from the same class access each other's private variables?

Private means "private to the class", NOT "private to the object". So two objects of the same class could access each other's private data.

Can objects of same class access each others private fields?

Any method within your class can access the private data of any instance of that class; there's not a way to keep data private to within an instance unless you forbid methods that explicitly access private data members of other instances.


2 Answers

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.

like image 116
Keith Avatar answered Oct 21 '22 13:10

Keith


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).

like image 36
Petar Ivanov Avatar answered Oct 21 '22 14:10

Petar Ivanov