C++ Operator Overloading Comparison operators

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

You can overload all comparison operators:

  • == and !=
  • > and <
  • >= and <=

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 that does operators do is compare, so they shouldn't modify the objects. Passing by & (reference) is faster than by value, and to make sure that the operators don't modify it, it is a const-reference.

Note that the operators inside the class/struct are defined as const, the reason for this is that without the functions being const, comparing const objects would not be possible, as the compiler doesn't know that the operators don't modify anything.



Got any C++ Question?