...

/

User-defined and Auto-generated Comparison Operators

User-defined and Auto-generated Comparison Operators

Visualize the interplay of user-defined and auto-generated operators with an example.

We'll cover the following...

When you can define one of the six comparison operators and also auto-generate all of them using the spaceship operator, there is one question: Which one has the higher priority? For example, the implementation MyInt has a user-defined less than and equal to operator and also the compiler-generated six comparison operators. Let’s see what happens.

Press + to interact
#include <compare>
#include <iostream>
class MyInt {
public:
constexpr explicit MyInt(int val): value{val} { }
bool operator == (const MyInt& rhs) const {
std::cout << "== " << '\n';
return value == rhs.value;
}
bool operator < (const MyInt& rhs) const {
std::cout << "< " << '\n';
return value < rhs.value;
}
auto operator<=>(const MyInt& rhs) const = default;
private:
int value;
};
int main() {
MyInt myInt2011(2011);
MyInt myInt2014(2014);
myInt2011 == myInt2014;
myInt2011 != myInt2014;
myInt2011 < myInt2014;
myInt2011 <= myInt2014;
myInt2011 > myInt2014;
myInt2011 >= myInt2014;
}

To see the user-defined == and < operator in action, I ...