Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. Operators are functions
    4. Equality: ==
    5. Ordering: <=>
    6. What <=> returns
    7. Writing <=> yourself
    8. [] and ()
    9. Making your type printable
    10. Hidden friends
    11. Which one should I use?
    12. Under the hood
    13. Common pitfalls
    14. A format spec your formatter doesn’t read
    15. A hand-written <=> without ==
    16. k * v when only v * k exists
    17. Try it yourself

    Module 4 · Your own types

    4.4Operators and comparisons with <=>

    Give your own types +, +=, ==, [] and (), get all six comparisons from one defaulted <=>, sort a vector of your type, and print it with std::println through a std::formatter.

    About 30 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. Operators are functions
    4. Equality: ==
    5. Ordering: <=>
    6. What <=> returns
    7. Writing <=> yourself
    8. [] and ()
    9. Making your type printable
    10. Hidden friends
    11. Which one should I use?
    12. Under the hood
    13. Common pitfalls
    14. A format spec your formatter doesn’t read
    15. A hand-written <=> without ==
    16. k * v when only v * k exists
    17. Try it yourself

    Key terms

    operator overloading
    Giving an operator a meaning for your own type by writing a function named operator plus the symbol, like operator+.
    non-member function
    A function declared outside any class. a + b can call a non-member operator+(a, b).
    defaulted comparison
    A comparison marked = default: the compiler compares the members one by one, in the order they're declared.
    operator<=> (three-way comparison)
    Compares two values once and says whether the first is less, equal or greater. C++ uses it for <, <=, > and >=.
    std::strong_ordering, std::partial_ordering
    What <=> returns: less, equal or greater, plus unordered for a partial ordering, where some values (like a floating-point NaN) can't be compared.
    function object
    An object with an operator(), so you can call it like a function.
    std::formatter<T>
    The standard library type that tells std::format and std::println how to turn a T into text.
    hidden friend
    A friend function defined inside a class: a non-member function that may use the class's private members, and that the compiler finds only when an argument has the class's type.

    a + b works for numbers, and a == b works for strings. For a type you write yourself, like a 2D position or a spot on a chromosome, neither works until you say what it means. You do that by writing functions with special names, like operator+. This lesson shows the operators worth writing, how one line gives your type every comparison so a vector of it can be sorted, and how to make it printable with std::println.

    In 30 seconds

    • An operator is a function with a special name: a + b calls operator+(a, b). Write one only when its meaning for your type is obvious.
    • Write += as a member function and + as a non-member built on it. [] and () must be members.
    • auto operator<=>(const T&) const = default; gives your type all six comparisons, member by member. Then std::ranges::sort can sort a vector of it.
    • std::println prints your type once you write a std::formatter<T> specialization: a parse and a format function.

    Operators are functions

    Vec2 is a 2D vector of floats, the kind that holds a position, a velocity or a 2D embedding. Adding two of them should add their xs and their ys:

    #include <print>
    
    struct Vec2 {
        float x;
        float y;
    
        Vec2& operator+=(const Vec2& other) {
            x += other.x;
            y += other.y;
            return *this;
        }
    };
    
    Vec2 operator+(Vec2 a, const Vec2& b) {
        a += b;
        return a;
    }
    
    Vec2 operator*(Vec2 v, float k) {
        return {v.x * k, v.y * k};
    }
    
    int main() {
        Vec2 position{1.0f, 2.0f};
        Vec2 velocity{0.5f, -1.0f};
        position += velocity; // position.operator+=(velocity)
        Vec2 next = position + velocity * 2.0f;
        std::println("{} {}", next.x, next.y);
    }

    Output

    2.5 -1
    • position += velocity calls the member function position.operator+=(velocity). It changes position and returns *this by reference, the convention for every =-style operator, as for copy assignment in Copy and move.
    • position + velocity * 2.0f calls operator+(position, operator*(velocity, 2.0f)). The usual precedence still holds: * before +.
    • operator+ is a non-member function: it’s declared outside the class and takes both sides as parameters. It takes a by value because it needs a copy to return anyway, adds b to it with +=, and returns it. Writing + in terms of += keeps the arithmetic in one place.

    You can overload almost every operator, but do it only when a reader would guess what it does. + on two vectors adds them; + on two database connections means nothing, so give that a named function instead.

    Equality: ==

    a == b calls operator==. Two Locus values, positions on a chromosome, are equal when both members are equal. That’s what the compiler writes when you mark operator== as = default:

    #include <print>
    
    struct Locus {
        int chromosome;
        long position;
    
        bool operator==(const Locus&) const = default;
    };
    
    int main() {
        Locus a{1, 900};
        Locus b{1, 900};
        Locus c{2, 900};
        std::println("{} {} {}", a == b, a == c, a != c);
    }

    Output

    true false true

    A defaulted comparison compares the members one by one, in the order they’re declared. You get != with it: since C++20, the compiler turns a != c into !(a == c). The const after the parameter list, from Structs and classes, says the comparison doesn’t change a.

    Ordering: <=>

    <, <=, > and >= come from one operator, <=>, the three-way comparison. a <=> b compares once and says whether a is less than, equal to or greater than b. Mark it = default and you get all six comparisons, because a defaulted <=> also gives you a defaulted ==:

    #include <algorithm>
    #include <print>
    #include <vector>
    
    struct Locus {
        int chromosome;
        long position;
    
        auto operator<=>(const Locus&) const = default;
    };
    
    int main() {
        Locus a{1, 900};
        Locus b{2, 100};
        std::println("{} {} {}", a < b, a >= b, a == b);
    
        std::vector<Locus> loci = {{2, 500}, {1, 900}, {1, 100}};
        std::ranges::sort(loci);
        for (const Locus& locus : loci) {
            std::println("chr{}:{}", locus.chromosome, locus.position);
        }
    }

    Output

    true false false
    chr1:100
    chr1:900
    chr2:500

    The defaulted <=> compares chromosome first, and only when those are equal, position. That’s lexicographic order, the order of words in a dictionary: a < b because chromosome 1 comes before 2, whatever the positions. To sort by position first, declare position first.

    std::ranges::sort(loci) (from <algorithm>) sorts the whole vector in place using <. Iterators and algorithms covers it and the other algorithms; all it needs from Locus is the comparisons.

    Key ideaOne line, six comparisons

    auto operator<=>(const T&) const = default; gives ==, !=, <, <=, > and >=, all consistent with each other. Before C++20, you wrote all six by hand, and it was easy for one to disagree with the others. A defaulted <=> usually replaces all of them.

    What <=> returns

    <=> doesn’t return a bool. For integers, it returns a std::strong_ordering (from <compare>), whose value is less, equal or greater. You can compare the result with 0: (a <=> b) < 0 means a is less than b.

    #include <compare>
    #include <limits>
    #include <print>
    
    std::strong_ordering order = 3 <=> 5;
    std::println("{} {}", order < 0, order == std::strong_ordering::less);
    
    double nan = std::numeric_limits<double>::quiet_NaN();
    std::partial_ordering maybe = 1.0 <=> nan;
    std::println("{}", maybe == std::partial_ordering::unordered);

    Output

    true true
    true

    Floating-point numbers give a std::partial_ordering, which has a fourth value, unordered. NaN (Not a Number) is a special floating-point value that marks an invalid result, such as the square root of a negative number. It isn’t less than, equal to or greater than anything, even itself. A third kind, std::weak_ordering, is for values that compare equal but can still differ, like names compared without case. With auto as the return type, a defaulted <=> picks the weakest kind among its members: a struct with a double member gets std::partial_ordering.

    Writing <=> yourself

    When the order you want isn’t the member order, write <=> yourself. Here alignments are ordered by score alone, and the read name doesn’t count:

    #include <compare>
    #include <print>
    #include <string>
    
    struct Alignment {
        std::string read;
        int score;
    
        std::strong_ordering operator<=>(const Alignment& other) const {
            return score <=> other.score;
        }
        bool operator==(const Alignment& other) const {
            return score == other.score;
        }
    };
    
    int main() {
        Alignment a{"read_1", 40};
        Alignment b{"read_2", 55};
        Alignment c{"read_3", 40};
        std::println("{} {} {}", b > c, a < b, a == c);
    }

    Output

    true true true

    A hand-written <=> doesn’t give you ==: only a defaulted one does. So write == too, and make the two agree. Common pitfalls shows what happens when it’s missing.

    [] and ()

    [] and () must be member functions. operator[] gives your type indexing like a std::vector. operator() makes an object callable like a function, as in the std::visit visitors of optional, variant and tuple; an object like that is a function object:

    #include <cstddef>
    #include <print>
    #include <string>
    #include <utility>
    
    class Sequence {
    public:
        explicit Sequence(std::string bases) : bases_(std::move(bases)) {}
        char operator[](std::size_t i) const { return bases_[i]; }
        char& operator[](std::size_t i) { return bases_[i]; }
    
    private:
        std::string bases_;
    };
    
    struct MinQuality {
        int threshold;
        bool operator()(int quality) const { return quality >= threshold; }
    };
    
    int main() {
        Sequence read("ACGTTA");
        read[0] = 'G'; // the non-const version: returns char&
        std::println("{} {}", read[0], read[3]);
        MinQuality good{20};
        std::println("{} {}", good(35), good(12));
    }

    Output

    G T
    true false

    Sequence has two operator[]s. The const one returns a copy of the char, for reading a const Sequence. The other returns a char&, a reference into bases_, so read[0] = 'G' changes the stored base. good(35) calls good.operator()(35): the object carries its threshold with it. Lambdas are a short way to write objects like this.

    Making your type printable

    std::println("{}", locus) needs to know how to turn a Locus into text. It asks std::formatter<Locus>, a type the standard library declares but leaves for you to write. Without one, the call doesn’t compile, with the same “std::formatter must be specialized” error that Pointers showed for an int*.

    Writing that version for your type is a specialization: template <> and the name std::formatter<Locus> say “this is std::formatter for Locus”. Class templates explains specializations; this shape is all you need to copy.

    #include <algorithm>
    #include <format>
    #include <print>
    #include <vector>
    
    struct Locus {
        int chromosome;
        long position;
    
        auto operator<=>(const Locus&) const = default;
    };
    
    template <>
    struct std::formatter<Locus> {
        constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); }
        auto format(const Locus& locus, auto& ctx) const {
            return std::format_to(ctx.out(), "chr{}:{}", locus.chromosome,
                                  locus.position);
        }
    };
    
    int main() {
        std::vector<Locus> loci = {{2, 500}, {1, 900}, {1, 100}};
        std::ranges::sort(loci);
        std::println("first: {}", loci[0]);
        std::println("{}", loci);
    }

    Output

    first: chr1:100
    [chr1:100, chr1:900, chr2:500]

    A formatter has two functions:

    • parse reads the format spec, the part after : in {:>12}. Returning ctx.begin() without reading anything means “this type takes no spec”, so only a plain {} is allowed. It’s constexpr because the format string is checked when you compile, as Printing and reading showed.
    • format writes the text. std::format_to(ctx.out(), …) works like std::format, but writes to the output position the context gives you and returns where it stopped, which is what format must return.

    Once Locus is printable, so is a std::vector<Locus>: the vector’s formatter prints the brackets and commas and calls yours for each element. That’s why ctx is declared auto&, which makes format accept any context type (Function templates explains auto parameters). The library uses more than one context type, and a format that names only std::format_context& prints a Locus but not a vector of them.

    Hidden friends

    friend before a function declared inside a class makes it a non-member function that can still use the class’s private members. Define it right there, inside the class, and it’s a hidden friend: the compiler only looks at it when one of the arguments is that class, which keeps it out of the way, and out of the error messages, when you use + on other types.

    #include <print>
    
    class Vec2 {
    public:
        Vec2(float x, float y) : x_(x), y_(y) {}
        float x() const { return x_; }
        float y() const { return y_; }
    
        friend Vec2 operator+(const Vec2& a, const Vec2& b) {
            return {a.x_ + b.x_, a.y_ + b.y_};
        }
        friend bool operator==(const Vec2&, const Vec2&) = default;
    
    private:
        float x_;
        float y_;
    };
    
    int main() {
        Vec2 sum = Vec2(1.0f, 2.0f) + Vec2(0.5f, 0.5f);
        std::println("{} {} {}", sum.x(), sum.y(), sum == Vec2(1.5f, 2.5f));
    }

    Output

    1.5 2.5 true

    operator+ reads x_ and y_ directly, though they’re private, and a defaulted comparison can be a hidden friend too. Many libraries write all their operators this way. For your own types, either style works; hidden friends are the tidier default.

    Which one should I use?

    WhatWhenWhyHow
    Defaulted <=>Your type has an order, and member order is the right one.One line gives all six comparisons, and sorting works.auto operator<=>(const T&) const = default;
    Defaulted == onlyEquality makes sense but “less than” doesn’t, like for a 2D vector.== and !=, without an order nobody should rely on.bool operator==(const T&) const = default;
    Hand-written <=> and ==Only some members count, or the order isn’t member order.You choose what to compare.Write both, and make them agree.
    += and +, [], ()The meaning is what a reader would guess: math on math types, indexing into a container, calling a function object.Code reads like the math or the container it models.+= as a member; + built on it, as a non-member or hidden friend.
    std::formatter<T>You want to print the type with std::println or std::format.It prints like a built-in type, also inside containers.parse plus format; build on std::formatter<std::string> to accept specs.

    Rule of thumb: default <=> (or ==) whenever you can, and give a type other operators only when nobody would need to look up what they do.

    Under the hood

    An overloaded operator is an ordinary function call; only the spelling is different. Comparisons add one more step: when a type has no operator< of its own, the compiler rewrites a < b as (a <=> b) < 0, and in the same way a != b as !(a == b). A <=> that prints shows it being called for both < and >=:

    #include <compare>
    #include <print>
    
    struct Score {
        int value;
    
        std::strong_ordering operator<=>(const Score& other) const {
            std::println("  <=> on {} and {}", value, other.value);
            return value <=> other.value;
        }
    };
    
    int main() {
        Score a{40};
        Score b{55};
        std::println("a < b:");
        bool less = a < b; // (a <=> b) < 0
        std::println("a >= b:");
        bool at_least = a >= b; // (a <=> b) >= 0
        std::println("{} {}", less, at_least);
    }

    Output

    a < b:
      <=> on 40 and 55
    a >= b:
      <=> on 40 and 55
    true false

    A defaulted <=> compares the members in order and stops at the first one that differs, so two Locus values on different chromosomes are told apart by their first member alone. == is kept separate from <=> for speed: two std::strings of different lengths can’t be equal, so their == can check the sizes first and skip the characters, which <=> can’t do because it must find which one comes first.

    Common pitfalls

    A format spec your formatter doesn’t read

    The formatter above takes no spec, so {:>12}, which asks for right alignment in 12 columns, is an error. Its parse stops before >12, and the compile-time check fails:

    #include <format>
    #include <print>
    
    struct Locus {
        int chromosome;
        long position;
    };
    
    template <>
    struct std::formatter<Locus> {
        constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); }
        auto format(const Locus& locus, auto& ctx) const {
            return std::format_to(ctx.out(), "chr{}:{}", locus.chromosome,
                                  locus.position);
        }
    };
    
    int main() {
        std::println("[{:>12}]", Locus{1, 900});
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:19:18: error: call to consteval function ‘std::basic_format_string<char, Locus>("[{:>12}]")’ is not a constant expression
       19 |     std::println("[{:>12}]", Locus{1, 900});
          |                  ^~~~~~~~~~
    compilation terminated due to -fmax-errors=1.

    To accept the specs a string accepts, build your formatter on the string formatter: : std::formatter<std::string> after the name gives yours everything that one has, including its parse, which reads the width, fill and alignment. (Inheritance and virtual functions covers building one class on another.) Drop your own parse, and have format build the text and hand it to the string formatter’s format, which pads it:

    #include <format>
    #include <print>
    #include <string>
    
    struct Locus {
        int chromosome;
        long position;
    };
    
    template <>
    struct std::formatter<Locus> : std::formatter<std::string> {
        auto format(const Locus& locus, auto& ctx) const {
            std::string text =
                std::format("chr{}:{}", locus.chromosome, locus.position);
            return std::formatter<std::string>::format(text, ctx);
        }
    };
    
    int main() {
        std::println("[{:>12}] [{:-<12}]", Locus{1, 900}, Locus{2, 5});
    }

    Output

    [    chr1:900] [chr2:5------]

    A hand-written <=> without ==

    Only a defaulted <=> brings a defaulted == with it. Write <=> yourself and a < b works, but a == b doesn’t compile:

    #include <compare>
    #include <string>
    
    struct Alignment {
        std::string read;
        int score;
    
        std::strong_ordering operator<=>(const Alignment& other) const {
            return score <=> other.score;
        }
    };
    
    int main() {
        Alignment a{"read_1", 40};
        Alignment b{"read_2", 40};
        bool same = a == b;
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:16:19: error: no match for ‘operator==’ (operand types are ‘Alignment’ and ‘Alignment’)
       16 |     bool same = a == b;
          |                 ~ ^~ ~
          |                 |    |
          |                 |    Alignment
          |                 Alignment

    The fix is to write operator== as well, comparing the same members as <=>, as in the Alignment example above.

    k * v when only v * k exists

    operator*(Vec2, float) handles velocity * 2.0f, but not 2.0f * velocity: the compiler doesn’t swap the sides for you.

    struct Vec2 {
        float x;
        float y;
    
        friend Vec2 operator*(const Vec2& v, float k) { return {v.x * k, v.y * k}; }
    };
    
    int main() {
        Vec2 velocity{0.5f, -1.0f};
        Vec2 step = 2.0f * velocity;
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:10:22: error: no match for ‘operator*’ (operand types are ‘float’ and ‘Vec2’)
       10 |     Vec2 step = 2.0f * velocity;
          |                 ~~~~ ^ ~~~~~~~~
          |                 |      |
          |                 float  Vec2
    main.cpp:10:22: note: there is 1 candidate
       10 |     Vec2 step = 2.0f * velocity;
          |                 ~~~~~^~~~~~~~~~
    main.cpp:5:17: note: candidate 1: ‘Vec2 operator*(const Vec2&, float)’
        5 |     friend Vec2 operator*(const Vec2& v, float k) { return {v.x * k, v.y * k}; }
          |                 ^~~~~~~~
    main.cpp:5:39: note: no known conversion for argument 1 from ‘float’ to ‘const Vec2&’
        5 |     friend Vec2 operator*(const Vec2& v, float k) { return {v.x * k, v.y * k}; }
          |                           ~~~~~~~~~~~~^

    If both orders make sense, write both, the second one calling the first: friend Vec2 operator*(float k, const Vec2& v) { return v * k; }.

    Try it yourself

    Try it yourself

    Date holds the day a sample was collected. Make dates sortable with a defaulted <=>, make them print as 2026-03-07 with a std::formatter<Date>, then sort samples and print the whole vector with one std::println.

    #include <print>
    #include <vector>
    
    struct Date {
        int year;
        int month;
        int day;
    };
    
    int main() {
        std::vector<Date> samples = {{2026, 3, 7}, {2025, 11, 30}, {2026, 1, 15}};
        for (const Date& d : samples) {
            std::println("{}-{}-{}", d.year, d.month, d.day);
        }
    }

    Expected output

    [2025-11-30, 2026-01-15, 2026-03-07]
    Show a hint

    Add auto operator<=>(const Date&) const = default; to Date. For the formatter, copy the Locus one and use the format string {}-{:02}-{:02}. Then sort with std::ranges::sort(samples) and print the whole vector with one std::println.

    Show a solution
    #include <algorithm>
    #include <format>
    #include <print>
    #include <vector>
    
    struct Date {
        int year;
        int month;
        int day;
    
        auto operator<=>(const Date&) const = default;
    };
    
    template <>
    struct std::formatter<Date> {
        constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); }
        auto format(const Date& d, auto& ctx) const {
            return std::format_to(ctx.out(), "{}-{:02}-{:02}", d.year, d.month,
                                  d.day);
        }
    };
    
    int main() {
        std::vector<Date> samples = {{2026, 3, 7}, {2025, 11, 30}, {2026, 1, 15}};
        std::ranges::sort(samples);
        std::println("{}", samples);
    }

    The defaulted <=> compares year, then month, then day, which is date order because the members are declared in that order. std::ranges::sort uses it. The formatter's {:02} pads the month and day to two digits with zeros, and printing the vector calls the formatter for each element.

    Saved in this browser only.