CodeBlanks Logo Icon CodeBlanks

Spaceship operator

Learn the C++20 spaceship (<=>) operator.

The spaceship operator (<=>)

The C++20 spaceship operator (<=>) automatically generates all comparison operators with a single function. With = default the compiler compares members in order.

Example: auto operator<=>(const Version&) const = default;. This single line generates ==, !=, <, <=, >, >= all at once. The #include <compare> header is required. You can also write the body by hand instead of = default, but default is enough in most cases. This greatly reduces comparison code.

Default comparison behavior

With = default the operator<=> compares the class members in declaration order. The first differing member gives the result.

Example: in class Version { int major; int minor; }; first major is compared. If equal, minor is compared. So Version(1, 5) < Version(2, 0) is true because 1 < 2. Version(1, 5) < Version(1, 7) is also true because major is equal and 5 < 7. This behavior is ideal for hierarchical data like version numbers.

Practice Add <=> to the Version class

Add the spaceship operator to the Version class in the starting code: auto operator<=>(const Version& other) const = default;. In main compare a < b; print "Less" if less, "More" otherwise.

Starter code

main.cpp
#include <iostream>
#include <compare>

class Version {
public:
    int major;
    int minor;
    Version(int maj, int min) : major(maj), minor(min) {}
    // Add the comparison operator
};

int main() {
    Version a(1, 0);
    Version b(2, 0);
    // Compare and print the result
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <compare>

class Version {
public:
    int major;
    int minor;
    Version(int maj, int min) : major(maj), minor(min) {}
    auto operator<=>(const Version& other) const = default;
};

int main() {
    Version a(1, 0);
    Version b(2, 0);
    if (a < b) {
        std::cout << "Less";
    } else {
        std::cout << "More";
    }
    return 0;
}

Expected output

Less

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each piece to its role

Term Meaning
<=> Spaceship operator
= default Automatic generation
#include <compare> Header file
auto Return type deduction

2 How many operators does operator<=> generate?

main.cpp
auto operator<=>(const Version&) const = default;
  • Six Correct answer
  • Two
  • One
  • Ten

Explanation: <=> generates six operators: ==, !=, <, <=, >, >=.

3 Spaceship operator signature

Question
auto ____(const Version& other) const = default;
Answer
auto operator<=>(const Version& other) const = default;

Explanation: operator<=> is the spaceship operator.

All lessons in Intermediate