Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison operator overloading

Tags:

c++

operators

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?

like image 735
blaze Avatar asked May 13 '12 22:05

blaze


People also ask

What is comparison operator overloading?

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.

Can comparison operators be overloaded?

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.

What are the 5 comparison operators?

Comparison operators — operators that compare values and return true or false . The operators include: > , < , >= , <= , === , and !==


1 Answers

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.

like image 174
zneak Avatar answered Sep 24 '22 09:09

zneak