4 Member operator overloading

In our previous example, we overloaded the == (equal) operator outside the context of class X. However, a careful examination confirms that the function only works in class X objects. It makes sense to make this a member operator of class X. We can do this:

class X
{
    int i,j;
  // ...
  public:
    int getI(void); // get the value of i
    int getJ(void); // get the value of j
    bool operator== (X b); // equality check
};
  
bool X::operator== (X b)
{
  return (i == b.getI()) && (j == b.getJ());
}

What happened to parameter a of the operator? It is now the implicit invoking object of the member operator ==! That's why we can just refer to members a and b. Note that because == is now a member operator, it has full access to all private members. As a result, we can simplify the code even more, as follows:

bool X::operator== (X b)
{
  return (i == b.i) && (j == b.j);
}

Cool, eh? Well, wait till you read the next section!



Copyright © 2006-09-12 by Tak Auyeung