Alessio
Alessio

Reputation: 19

Strange behaviour when accessing private attribute in C++

I experienced a strange behaviour trying to access a private attribute. Consider the following code:

class CLASSE
{
    private:
         int X;
    public:
         CLASSE(int x) { X = x; }
         int  GetX(){ return X; }
         void CopyFrom(CLASSE Src){ X = Src.X; }
};

main ()
{
 CLASSE A = 123;
 CLASSE B = 456;

 cout << "A = " << A.GetX() << endl;
 cout << "B = " << B.GetX() << endl << endl;

 A.CopyFrom (B);
 cout << "A = " << A.GetX() << endl;
 // cout << "A = " << A.X << endl; *** ERROR: CLASSE::X is private
}

In the main(), trying to access private attribute X correctly returns an error. I was expecting the same in this situation instead, access to private attribute X in method CopyFrom is allowed (but i'd expect an error). The code has been tested both on DevC and Codeblocks.

Is there an explanation for this behaviour?

Upvotes: 0

Views: 117

Answers (1)

sagi
sagi

Reputation: 40491

Every method of a class has access to all its data members, including private members.

EDIT: as @StoryTeller mentioned, they also has access to private members of other objects of the same class.

This is also true for private member functions .

Upvotes: 11

Related Questions