Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Defaulted comparison operator

`= default` requests a compiler-generated implementation of a comparison operator. Defaulted `operator==` and `operator<=>` compare class subobjects in a defined order: the former tests equality, and the latter determines ordering. Defaulted secondary operators such as `!=` and `<` use rewritten comparisons instead of comparing subobjects themselves.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

struct T {
    bool operator==(const T&) const = default;
    auto operator<=>(const T&) const = default;
};

A Defaulted comparison operator is a comparison operator implemented by the compiler through = default. It must be a non-template function: either a non-static member or a friend of a class. A definition using = default inside the class must be that function's first declaration.

Comparison visits direct base classes first, then non-static data members, in declaration order. Arrays are expanded into their elements. operator== must return bool and stops at the first unequal pair. operator<=> compares lexicographically: the first pair producing a nonzero comparison result determines the result. Thus, in the example, a < b is true even though 9 > 0.

For auto operator<=>, the compiler deduces the common comparison category of the subobjects: std::strong_ordering, std::weak_ordering, or std::partial_ordering. If the class does not explicitly declare a member or friend named operator==, an in-class defaulted operator<=> also implicitly declares a defaulted operator==. Defaulting operator== alone does not provide ordering.

The secondary operators !=, <, <=, > and >= can also be defaulted; they require a bool result and a valid rewritten comparison rather than independently comparing members. In typical usage, expressions use rewriting based on == or <=> without separate declarations of these operators.

= default does not guarantee validity: an inaccessible or unsupported subobject comparison can cause the operator to be defined as deleted. This also applies to == and <=> for classes with reference data members or variant members of unions. Write a custom implementation when not every subobject should contribute to the result.

Examples

#include <compare>
#include <iostream>

struct Point {
    int x;
    int y;
    auto operator<=>(const Point&) const = default;
};

int main() {
    const Point a{1, 9};
    const Point b{2, 0};
    const Point c{1, 9};

    std::cout << std::boolalpha;
    std::cout << (a == c) << '\n';
    std::cout << (a != b) << '\n';
    std::cout << (a < b) << '\n';
}

Result

true
true
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources