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?
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.