skip to content

How do you make two C++ Money objects comparable with ==, and what does C++20's = default generate for it?

level: juniorimportance: must knowfreq 70%

answer

  1. a const member returning bool
  2. compare every member yourself
  3. C++20 can write it for you
  4. declaration order, first mismatch
  5. != comes for free in C++20

basics

~10 s

Declare bool operator==(const Money&) const and compare the members. Since C++20, = default makes the compiler compare each base and member in declaration order, and a != b is rewritten as !(a == b).

solid answer

~40 s

C++ gives a class no `==` of its own, so `a == b` on two `Money` objects does not compile until you declare one. The classic form is a `const` member (or a non-member taking two `const Money&`) that returns `bool` and compares the members that make up the value, plus a matching `operator!=`. **Since C++20** you can write `bool operator==(const Money&) const = default;`: the compiler compares the base classes and then the non-static data members **in declaration order**, stopping at the first pair that is not equal. C++20 also **rewrites** `a != b` as `!(a == b)` and tries the reversed `b == a`, so one `==` serves both operators and both operand orders. A defaulted `==` is defined as deleted if a member has no usable `==` or is a reference.

code

cpp · 17 lines
cpp
#include <cstdio>

enum class Currency { USD, EUR };

struct Money {
    Currency currency;
    long long cents;

    bool operator==(const Money&) const = default;   // C++20: memberwise, in declaration order
};

int main() {
    Money a{Currency::USD, 1000}, b{Currency::USD, 1000}, c{Currency::EUR, 1000};
    std::printf("a == b: %d\n", a == b);   // 1
    std::printf("a == c: %d\n", a == c);   // 0: currency differs
    std::printf("a != c: %d\n", a != c);   // 1: rewritten as !(a == c)
}

go deeper

for a junior

Remember the signature, a const member taking const Money& and returning bool, and that C++20 lets you write = default.

for a middle

Explain what the defaulted body compares and in which order, why != comes for free in C++20, and why byte-wise comparison is wrong.

for a senior

Spot the members that should not take part in equality, and the C++20 ambiguity a non-const member == causes after a standard upgrade.

for a principal

Decide whether value types default their comparisons as a team rule, and how to audit types where some members are not part of the value.

## Why a class needs its own == For a class type, `a == b` is an ordinary function call in disguise: the compiler looks for an `operator==` that accepts the two operands and runs overload resolution on what it finds. A struct gets an implicitly declared copy constructor and assignment operator, but **no comparison operators**. Comparing raw bytes would be wrong anyway: padding bytes have unspecified values, and a member such as `std::string` owns a pointer whose value says nothing about the text. ## The hand-written form (C++98 to C++17) Before C++20 the idiomatic pair looks like this: ```cpp struct Money { Currency currency; long long cents; bool operator==(const Money& rhs) const { return currency == rhs.currency && cents == rhs.cents; } bool operator!=(const Money& rhs) const { return !(*this == rhs); } }; ``` Three conventions matter: - The function is **`const`** (or a non-member taking `const Money&` twice): comparing must not modify either operand, and a `const Money` must be comparable. - It returns **`bool`**. - `!=` is written **in terms of `==`**, so the two can never disagree. ## The defaulted form (C++20) C++20 lets the compiler write the body: `bool operator==(const Money&) const = default;`. The standard's rules for a **defaulted equality operator** are: 1. It must be a member or friend of the class, with two parameters of type `const Money&` (the implicit object counts as the first) or two of type `Money`, and it must return `bool`. 2. It compares the **direct base classes in declaration order, then the non-static data members in declaration order**; array members are compared element by element. 3. It returns `false` at the first pair whose `==` is false, and `true` if there is none. 4. It is **defined as deleted** if any subobject has no usable `==`, or if the class has a reference member or a variant member (an anonymous union). The code example shows the result: two USD amounts of 1000 cents compare equal, and a EUR amount of the same size does not, because `currency` differs. ## Member or friend The defaulted form has a few placement rules of its own: - It may be a **`const` member** taking `const Money&`, or a **friend** taking two `const Money&` or two `Money` by value; mixing the two parameter types is rejected. - A defaulting declaration inside the class must be the **first declaration** of that operator. - It may also be defaulted **outside** the class, as long as `Money` is complete at that point, which lets a header declare it and a source file define it. - It is a **member or friend of the class** it compares; a free function or an enumeration cannot have a defaulted `==`. ## What C++20 changes at the call site The second half of the C++20 change is **rewritten candidates**. When the compiler sees `x != y` it also considers `!(x == y)`, and for `x == y` it also considers the **reversed** `y == x`. Consequences: - You no longer write `operator!=`; it is derived from `==`. - A member `==` now works with the class on the right as well, provided the left operand converts, because `5 == m` can be evaluated as `m == 5`. - A **non-`const` member `operator==`** becomes a trap: the normal and the reversed call need different conversions on the object, and clang warns `ISO C++20 considers use of overloaded operator '==' (with operand types 'Money' and 'Money') to be ambiguous despite there being a unique best viable function`, and suggests marking it `const`. ## Comparison table | | C++17 | C++20 and later | |---|---|---| | Body of `==` | written by hand | `= default` or by hand | | `!=` | written by hand | rewritten from `==` | | `5 == m` with a member `==` and a converting constructor | does not compile | uses the reversed candidate | | `<`, `>`, `<=`, `>=` | written by hand | rewritten from `<=>`, the three-way comparison operator | ## When not to default it Defaulting compares **every** member. If `Money` caches a formatted string, or carries an audit timestamp that should not affect equality, a defaulted `==` gives the wrong answer and must be written by hand. The rule of thumb in interviews: default `==` when the members *are* the value, write it when only some of them are.

  • Why not compare two Money objects with std::memcmp?
    Padding bytes between members have unspecified values, so two equal objects can differ byte for byte. It is also wrong for members that hold pointers, such as `std::string`, whose equality is about the pointed-to text. A memberwise `==`, hand-written or defaulted, compares values.
  • When is a defaulted operator== defined as deleted?
    When some base or member has no usable `==`, or when the class has a reference member or a variant member. The declaration still compiles; using `a == b` then fails, and clang explains which member blocked it.

  • The compiler generates operator== for every struct automatically
  • A defaulted operator== compares the raw bytes of the two objects
  • C++20 still requires a separate operator!= next to a defaulted ==
  • operator== can be a non-const member without consequences in C++20
  • A defaulted == compares members in alphabetical order

Assumes C++20 or later for = default on operator== and the rewritten != and reversed == candidates; C++17 needs both operators written by hand.