Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Overload != When == Overloaded

Say I have a class where I overloaded the operator == as such:

Class A {
  ...
  public:
    bool operator== (const A &rhs) const;
  ...
};

...

bool A::operator== (const A &rhs) const {
  ..
  return isEqual;
}

I already have the operator == return the proper Boolean value. Now I want to extend this to the simple opposite (!=). I would like to call the overloaded == operator and return the opposite, i.e. something of the nature

bool A::operator!= (const A &rhs) const {
  return !( this == A );
}

Is this possible? I know this will not work, but it exemplifies what I would like to have. I would like to keep only one parameter for the call: rhs. Any help would be appreciated, because I could not come up with an answer after several search attempts.

like image 696
Jake Z Avatar asked Aug 07 '26 12:08

Jake Z


2 Answers

You almost had it:

bool A::operator!= (const A &rhs) const {
  return !( *this == rhs );
}

Note that this is a pointer, not the object. You need to dereference it. On a related note, it is usually better to implement most binary operators as free functions rather than member functions.

like image 147
David Rodríguez - dribeas Avatar answered Aug 09 '26 01:08

David Rodríguez - dribeas


You don't have to do it on individual (per-class) basis.

The standard library already provides support for this approach, by declaring "default" template implementations for operators !=, >, <= and >=, which rely on user-provided operators == and <. These declarations are located in header <utility> and enclosed in namespace std::rel_ops.

Since these implementations are declared in namespace std::rel_ops, they are not found by default by name lookup. If you want to "activate" these definitions in your program, do

#include <utility>
using namespace std::rel_ops;

This, for example, will automatically derive operator != from your implementation of operator == for all classes in the translation unit. You can still override the mechanism by providing an explicit implementation of operator != for some specific class.

like image 29
AnT Avatar answered Aug 09 '26 02:08

AnT