Which is best practice (in this case):
bool Foo::operator==(const Foo& other) { return bar == other.bar; } // Implementation 1 bool Foo::operator!=(const Foo& other) { return bar != other.bar } // Implementation 2 bool Foo::operator!=(const Foo& other) { return !(*this == other); }
For operators like >, <, <=, >= I would go with implementation 2 when possible. However, for != I think implementation 1 is better since another method call is not made, is this correct?
Relational Operators Overloading in C++ which can be used to compare C++ built-in data types. You can overload any of these operators, which can be used to compare the objects of a class. Following example explains how a < operator can be overloaded and similar way you can overload other relational operators.
Overloading. The relational comparison operators ( < . <= , > , >= , = , <> ) can be overloaded, which means that a class or structure can redefine their behavior when an operand has the type of that class or structure.
Comparison operators — operators that compare values and return true or false . The operators include: > , < , >= , <= , === , and !==
The second implementation has the notable constraint that ==
will always be the boolean opposite of !=
. This is probably what you want, and it makes your code easier to maintain because you only have to change one implementation to keep the two in sync.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With