Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why == overloading can access private members of argument [duplicate]

Possible Duplicate:
why private value of the obj can be changed by class instance?

Consider the following (partial) code:

class Group {
    private:
      int id;

    public:
      void set_id(int);
      int get_id();
      bool operator==(const Group&);
};


bool Group::operator==(const Group& g) {
    if(g.id == this->id) {  /* id is private? */
            return true;
    }

    return false;
}

The code compiles and results seem proper. However, in the if part of the operator overloading implementation, we are directly accessing the private member of its argument - const Group& g, but isn't such an access invalid?

like image 558
WeaklyTyped Avatar asked Sep 18 '12 15:09

WeaklyTyped


2 Answers

Your operator== is a member of your Group class. Member functions can access any private members of that class, not only for this, but for any instance they can access.

If you think about it this behaviour is necessary, because otherwise access control would make methods for interaction of two or more instances (swap, copy constructors, operators) impossible, unless the object has a public accessor to any member variable, which is used in such a method. Often enough that isn't desirable from a design point of view. Furthermore it would raise the bar for access control to high ("if I simply make that member public, I can spare me the pain...").

Concluding this code is perfectly valid (although I don't see why the if is necessary, compared to simply using return g.id == this->id;)

like image 181
Grizzly Avatar answered Oct 26 '22 02:10

Grizzly


Access qualifiers are not controlling access on the instance level, but on the type level. Any member function of a instance of type T can access all the private members of any other instance of the very same type T.

Since the operator== is a member function it can access all the member variables of instances of the class it's member of.

like image 43
datenwolf Avatar answered Oct 26 '22 00:10

datenwolf