Member-only story
C++20 three-way comparison operator: Part 1

Introduction
In this tutorial series, I’ll discuss about the 3 way comparison operator , <=>
, introduced in C++20. This is a tutorial series split in several parts and hence I strongly encourage the readers to try out and experiment with the example I provide in each part.
In this part of the series, I’ll explain with example what problem the three way comparison operator, also known as the spaceship operator (and hence the title image), intends to solve.Without much ado, lets take a look at the problem it solves.
Lets say we create a custom object Int
as a wrapper class for int
.
class Int{
private:
int value{};
public:
Int() = default; //default ctor
Int(const int val): val_{val}{}
};
It is quite obvious that this class looks incomplete since it should provide all combinations of the comparison operators viz ==
, >=
, <=
, !=
, >
, <
. This makes sense since the object is intended to be used for comparison. So I overload these 6 operators as member functions[1][2].
To keep the idea easy to follow I provide the definition of only one of the friend operator: ==
:
class Int{
private:
int val_{};
public:
Int() =default;
Int(const int val)…