- Learn C++ - http://www.learncpp.com -

9.6 — Overloading the comparison operators

Overloading the comparison operators is comparatively simple (see what I did there?), as they follow the same patterns as we’ve seen in overloading other operators.

Because the comparison operators are all binary operators that do not modify their left operands, we will make our overloaded comparison operators friend functions.

Here’s an example Car class with an overloaded operator== and operator!=.

The code here should be straightforward. Because the result of operator!= is the opposite of operator==, we define operator!= in terms of operator==, which helps keep things simpler, more error free, and reduces the amount of code we have to write.

It doesn’t really make sense to overload operator> or operator< for the Car class. What does it mean for a Car to be greater or less than another Car? Greater than or less than isn’t a concept we normally apply to cars, so it’s better not to include those operators in the Car class, because the results of the operators (whatever you define them to be) would not be intuitive.

Here’s a different example with an overloaded operator>, operator<, operator>=, and operator<=:

This is also pretty straightforward.

Note that there is some redundancy here as well. operator> and operator<= are logical opposites, so one could be defined in terms of the other. operator< and operator>= are also logical opposites, and one could be defined in terms of the other. In this case, I chose not to do so because the function definitions are so simple, and the comparison operator in the function name line up nicely with the comparison operator in the return statement.

Quiz time

1) For the Cents example above, rewrite operators < and <= in terms of other overloaded operators.

Show Solution [1]

9.7 -- Overloading the increment and decrement operators [2]
Index [3]
9.5 -- Overloading unary operators +, -, and ! [4]