Comparison operators

suggest change

You can overload all comparison operators:

The recommended way to overload all those operators is by implementing only 2 operators (== and \<) and then using those to define the rest. Scroll down for explanation

Overloading outside of class/struct:

//Only implement those 2
bool operator==(const T& lhs, const T& rhs) { /* Compare */ }
bool operator<(const T& lhs, const T& rhs) { /* Compare */ }

//Now you can define the rest
bool operator!=(const T& lhs, const T& rhs) { return !(lhs == rhs); }
bool operator>(const T& lhs, const T& rhs) { return rhs < lhs; }
bool operator<=(const T& lhs, const T& rhs) { return !(lhs > rhs); }
bool operator>=(const T& lhs, const T& rhs) { return !(lhs < rhs); }

Overloading inside of class/struct:

//Note that the functions are const, because if they are not const, you wouldn't be able
//to call them if the object is const

//Only implement those 2
bool operator==(const T& rhs) const { /* Compare */ }
bool operator<(const T& rhs) const { /* Compare */ }

//Now you can define the rest
bool operator!=(const T& rhs) const { return !(*this == rhs); }
bool operator>(const T& rhs) const { return rhs < *this; }
bool operator<=(const T& rhs) const { return !(*this > rhs); }
bool operator>=(const T& rhs) const { return !(*this < rhs); }

The operators obviously return a bool, indicating true or false for the corresponding operation.

All of the operators take their arguments by const&, because the only thing operators do is compare, so they should not modify the objects. Passing by & (reference) is faster than by value, and to make sure that the operators do not modify the objects, the parameters are const references.

Note that the operators inside the class/struct are defined as const. Without that, comparing const objects would not be possible, because the compiler would not know that the operators do not modify anything.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents