C/C++ Arena

Step 2 of 5

operator== and !=

To compare your own types with ==, define operator==. It returns a bool and usually takes both sides by const&:

#include <iostream>
#include <string>

struct Version {
    int major, minor;
    std::string label;
};

bool operator==(const Version& a, const Version& b) {
    return a.major == b.major && a.minor == b.minor;
}

struct Point {
    int x, y;
    bool operator==(const Point&) const = default;
};

int main() {
    Version v1{2, 1, "stable"};
    Version v2{2, 1, "rc"};
    std::cout << (v1 == v2) << (v1 != v2) << "\n";
    std::cout << (Point{1, 2} == Point{1, 2}) << (Point{1, 2} == Point{2, 1}) << "\n";
}
10
10

You decide what "equal" means

Version's == deliberately ignores the label: two versions with the same numbers count as equal. Writing == by hand lets you choose which members matter.

C++20 conveniences

All six comparisons from one line

auto operator<=>(const T&) const = default; defines the three-way comparison (nicknamed the spaceship operator, from <compare>). The compiler then provides <, <=, > and >=, comparing members in the order they're declared, the way a dictionary compares words letter by letter. A defaulted <=> also gives you ==, so one line makes a type fully comparable and sortable:

#include <compare>
#include <iostream>

struct Release {
    int major, minor, patch;
    auto operator<=>(const Release&) const = default;
};

int main() {
    Release a{1, 4, 2}, b{1, 10, 0};
    std::cout << (a < b) << (a == b) << (b >= a) << "\n";
}
101

1.4.2 is less than 1.10.0 because minor is compared as a number (4 < 10), not as text.

Member or free function?

Point's operator is a member (declared inside the struct, with one parameter: the right-hand side, while *this is the left). Version's is a free function with both sides as parameters. Both work. Free functions are often preferred for symmetric operators like == and +, since they treat both sides the same way.

Your turn: write operator== for Score by hand. Two scores are equal if both teams' round counts match; the map name doesn't matter.

Previous: operator+ Next: Printing with operator<<