1
class classN
{
public:
bool operator== (const classN &o) const {//some logic here};
bool operator!= (const classN &o) const {return !(*this == o);};
};

I see this as the best way to write overloads of operator== and operator!=, as I need to change code only once. however, I've seen in different projects people writing actual code in both overloads. As I mention, I feel it's quite a big downside that if logic will be changed it should be changed in two places, with can leads to a bugs when you will forget to make similar change in other overload. But maybe there are some downsides I'm not aware of writing the way I've shown now, using return !(*this == o); ? Like calling to a operator== overload inside operator!= being too expensive, so it makes sense to write actual code with comparison of the class fields? Or something else?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Bruice
  • 543
  • 3
  • 11
  • 2
    There are no downsides. Additionally: once you upgrade your C++ compiler to one that supports the current C++ standard you won't even have to write it yourself, the compiler will write it for you. – Sam Varshavchik Jun 15 '21 at 11:55
  • Does this answer your question? [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – Richard Critten Jun 15 '21 at 11:57
  • DRY says this is the way to do it. You can also do the same thing with the other comparison operators. See the section *Comparison operators* here: https://stackoverflow.com/a/4421719/4342498 – NathanOliver Jun 15 '21 at 11:57

0 Answers0