3

Or in other words, would these 2 blocks be equal for the compiler:

if (a!=b){
// do something
}
if (!(a==b)){
// do something
}
rabl
  • 119
  • 4
  • 3
    No, but sematically speaking, your operator!= SHOULD just be implemented as `return !operator==(rhs);` (or vice versa) – franji1 Apr 05 '21 at 20:16
  • Or similarly, would it also override `(a<=b)`, as that’s reducible to `(a – Howlium Apr 05 '21 at 20:19
  • Is there ever a scenario where these 2 operators would be implemented without being directly dependant on the other? (Of course you wouldn't need to functionally program them to check for equality, but what would be an application of that) – rabl Apr 05 '21 at 20:20
  • [Boost.Lambda](https://www.boost.org/doc/libs/1_75_0/doc/html/lambda.html) used operator overloading to hack together lambda functions before C++11. In that library, all operator overloads returned a special functor object, and `==` and `!=` were both defined independently (namely, to delegate to the respective operator on their arguments) – Silvio Mayolo Apr 05 '21 at 21:46

2 Answers2

6

No. We can test this easily

#include <iostream>

class C {};

bool operator==(C, C) { return true; }

int main() {
  C a, b;
  std::cout << (a != b) << std::endl;
  return 0;
}

Produces (on gcc)

.code.tio.cpp: In function ‘int main()’:
.code.tio.cpp:9:19: error: no match for ‘operator!=’ (operand types are ‘C’ and ‘C’)
   std::cout << (a != b) << std::endl;
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
1

Operator overloads only give you what you are asking for, so overloading == will not affect !=. Therefore, (a != b) is not the same as (!(a == b)).

However, good practice is to overload both to avoid confusion.

Austin
  • 2,203
  • 3
  • 12
  • 28