which operators of the comparison (<=, >, ==, etc.) do You usually implement as your basic operators, which You can after use to implement the rest comparison operators or to make all possible comparisons among the classes?
-
1You may want to have a look at the great FAQ on operator overloading (http://stackoverflow.com/questions/4421706/operator-overloading/4421719#4421719), it covers your question too. – Matteo Italia Jan 03 '11 at 23:45
3 Answers
You can implement all six of the operators in terms of ==
and <
using the following equivalencies:
a != b => !(a == b)
a > b => b < a
a >= b => !(a < b)
a <= b => !(b < a)

- 348,265
- 75
- 913
- 977
-
3You can also do it using the < operator only since (a == b) is logically equivalent to !(a – Y.H. Jan 03 '11 at 23:49
I normally implement operator==
for objects and also operator!=
. Many objects do not have a collating sequence, so the comparison operators <, <=, >, >= do not make sense.
Also, by using boost::equality_comparable
and boost::less_than_comparable
only operator==
and operator<
need to be implemented. These can be found in boost/operators.hpp
.
Also, I have learned that placing comparison operators in base clases or interface classes can become quite tricky as they allow Descendent_A to be compared to Descendent_B, which are two different descendent classes.
Comparison operators should be implemented as needed in classes. Many classes do not need them. Also, beware of implementing them or defining them in base classes without considering the ramifications of inheritance.

- 56,849
- 17
- 98
- 154
For classes where they are applicable I usually implement operator<
and operator==
"natively" because of their prominence in standard algorithms and containers.
I then implement the other four in terms of these.
Another approach that I sometimes consider is implementing a "compare" function that returns 1
, 0
, or -1
in the style of strcmp
and the implement all the other operators in terms of this. I only do this if operator<
and operator==
look like they need to share much of the same code which seems to happen less often that I think.

- 755,051
- 104
- 632
- 656