Skip to content
Tutorials Center
My learning

Topics

Lesson 73 of 171 ยท Object-Oriented Programming

Operator Overloading

Learn C++ operator overloading - arithmetic and compound assignment, defaulted == and <=>, stream << and >>, subscript and call operators, member vs free functions, and good taste.

When you write a + b with two std::strings, v[3] on a std::vector or std::cout << x, you're calling functions. The standard library overloads operators so its types feel like built-in ones. Your own classes can do the same: a Vec2 can support a + b, a Money can print with <<, a Matrix can be indexed with m(1, 2), and almost any value type can get == and < for free with one line of C++20.

Used well, operator overloading makes code read like the math or the domain it models. Used badly, it hides surprising work behind innocent symbols. In this lesson you'll learn the syntax for each family of operators, when to write them as members and when as free functions (often hidden friends), how the defaulted == and <=> remove pages of boilerplate, and the rules and taste that keep overloads unsurprising.

The basic idea

An overloaded operator is a function named operator followed by the symbol: operator+, operator==, operator[]. When the compiler sees a + b and either operand has a class type, it looks for a matching operator+. It can be:

  • a member function, taking one fewer parameter: a + b becomes a.operator+(b),
  • a free function, taking every operand: a + b becomes operator+(a, b).

You can't invent new operators (**, <>), change an operator's precedence or associativity, or change how many operands it takes. And at least one operand must be a class or enum type, so you can't redefine int + int.

Arithmetic and compound assignment

The idiomatic recipe for arithmetic: write the compound assignment (+=) as a member that modifies *this and returns *this by reference, then write the plain operator (+) as a free function that copies the left operand and uses +=. One implementation, two operators, consistent behavior.

C++ A Vec2 with arithmetic operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Details worth copying:

  • operator+ takes its left operand by value. That copy is the result we modify and return, so no extra temporary is needed.
  • Writing both v * k and k * v matters. A member operator* could only handle v * k, because a member always gets its own class as the left operand.
  • += returns Vec2& so chains like (a += b) += c behave like they do for int.

Why free functions for symmetric operators

There's a second reason to prefer free functions for +, == and friends: implicit conversions apply to both operands. Vec2 has a non-explicit constructor from double, so Vec2{1, 2} + 5.0 converts 5.0 to Vec2{5, 0}. With a free operator+, 5.0 + Vec2{1, 2} works too. With a member, only the right operand could convert, and the expression would compile in one order but not the other. (Whether a conversion from double is a good idea for a vector is another question; for a Fraction from int it's natural.)

Comparison operators: == and <=>

Before C++20, a fully comparable type needed six operators: ==, !=, <, <=, >, >=. Now you write at most two, and often you just ask the compiler for them:

  • operator== gives you == and !=: the compiler rewrites a != b as !(a == b).
  • operator<=> (the "spaceship", or three-way comparison) gives you <, <=, > and >=: a < b is rewritten as (a <=> b) < 0.
  • Rewrites also work with swapped operands, so 5 == x finds x == 5.

Declaring them = default compares the members in declaration order, lexicographically, like comparing words letter by letter. Defaulting <=> also implicitly defaults ==.

C++ Defaulted comparisons sort a vector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

1.10.0 correctly sorts after 1.9.3, because the members are compared as numbers, not text.

Writing <=> yourself

When memberwise comparison isn't what the type means, write the operator. <=> returns one of three comparison categories from <compare>:

Type Meaning Example
std::strong_ordering equal values are indistinguishable integers, Version
std::weak_ordering "equivalent" values may still differ case-insensitive strings
std::partial_ordering some values aren't comparable at all double (NaN)

If you write a custom <=>, write == too: a custom <=> does not generate ==, because equality can often be checked faster (strings of different lengths can't be equal, for instance).

C++ A custom spaceship operator for fractions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

1 > half works because the operators are free functions and Fraction converts from long long, and because the compiler can use the reversed form of <=>. The cross-multiplication could overflow for huge values; a production fraction class would reduce by std::gcd first.

Stream operators << and >>

To print with std::cout and read with std::cin, overload operator<< and operator>> as free functions. They take the stream by non-const reference, return it so calls can chain, and >> must report bad input by setting the stream's fail state rather than throwing or printing.

C++ Reading and writing a type with streams

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The loop reads 12:30 and 7:05, then rejects 25:00 (the hour is out of range) by setting failbit, which ends the loop. alarm still holds the last good value, because >> only assigns after validating. Stream states are covered in depth in I/O Streams in Depth.

To use your type with std::print and std::format you specialize std::formatter instead of overloading an operator; Formatting with std::format and std::print shows how.

Subscript [] and function call ()

operator[] must be a member. Give it const and non-const overloads (see const Member Functions) so it works on both kinds of objects. Like std::vector, the convention is that [] doesn't check bounds and a separate at() does, though nothing stops you from checking in debug builds.

Since C++23, operator[] may take several arguments, so a matrix can be indexed as m[row, col]. Before that, libraries used operator() for this. operator() can take any number of parameters, which also makes objects callable like functions. Such objects are called function objects or functors, and every lambda is one (see Function Objects and std::function).

C++ Indexing a grid and calling a polynomial

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The non-const operator[] returns char&, which is what makes board[1, 2] = '#' an assignment into the grid.

Increment, decrement and conversion operators

Prefix and postfix ++ are told apart by a dummy int parameter. Prefix returns a reference to the updated object; postfix returns a copy of the old value, which is why prefix is the one to prefer for class types.

C++
class Counter {
public:
    Counter& operator++() { ++value_; return *this; }    // ++c
    Counter operator++(int) {                            // c++
        Counter old = *this;
        ++*this;
        return old;
    }
private:
    int value_ = 0;
};

A conversion operator lets an object convert to another type. Almost always mark it explicit. The main use is explicit operator bool(), which lets if (obj) and while (obj) work (those contexts allow explicit conversion to bool) without letting obj + 1 or int n = obj; compile by accident:

C++
class Connection {
public:
    explicit operator bool() const { return open_; }   // if (conn) { ... }
private:
    bool open_ = false;
};

Streams use exactly this, which is why while (std::cin >> alarm) works above.

Member or free function?

Operator Write it as Why
=, [], (), ->, conversion operators member (required) the language demands it
+=, -=, *=, ++, --, unary - member they modify or belong to one object
+, -, *, /, ==, <=> free (hidden friend) symmetric; conversions on both sides
<<, >> for streams free (often friend) the left operand is the stream

Rules and good taste

The language rules:

  • You can't overload ::, ., .*, ?:, sizeof, alignof, typeid or the cast keywords.
  • You can overload &&, || and ,, but don't: the overloads are ordinary functions, so both operands are always evaluated and short-circuiting is lost.
  • Overloading unary & (address-of) is legal and almost always a mistake; generic code uses std::addressof to cope with it.

The taste rules matter more:

  • Do what the built-in operator does. + adds or concatenates and doesn't modify its operands; == is an equivalence; < is a strict ordering. A + that writes to a database is a trap.
  • Keep related operators consistent. If a + b exists, a += b should exist and agree with it; if a == b, then !(a != b). Building + on += and defaulting comparisons gives you this for free.
  • Overload only when the meaning is obvious. matrix * vector is clear; user + group is not. A named function (add_member) is better than a clever operator.
  • Return the right type. Compound assignment and prefix ++ return T&; arithmetic returns T by value; comparisons return bool or an ordering; stream operators return the stream.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Vec2 has a member Vec2 operator*(double k) const. Which expression fails to compile?

    A member operator always takes its own class as the left operand. 2.0 * v needs a free function operator*(double, Vec2).
  2. 2. A struct declares only auto operator<=>(const S&) const = default;. Which operators can you use on S?

    Defaulting <=> also implicitly declares a defaulted ==. The compiler rewrites != from ==, and the four relational operators from <=>.
  3. 3. Why should you not overload operator&& for your class?

    An overloaded && is a normal function call, and all arguments of a call are evaluated first. Code relying on short-circuiting, like p && p->ok(), would then break.
  4. 4. What should a well-behaved operator>> do when the input text is invalid?

    Stream extraction reports errors through the stream state, so loops like while (in >> x) stop. Leaving the object unchanged keeps the last good value.
  5. 5. Why does the recommended operator+ take its left parameter by value, as in Vec2 operator+(Vec2 a, const Vec2& b)?

    The result of a + b is a new value. Taking a by value makes that copy up front; a += b modifies it and it is returned, often with no further copies.

Summary

  • An overloaded operator is a function named operator@, written as a member (one fewer parameter) or a free function.
  • Implement += as a member returning *this, then + as a free function built on it; provide both v * k and k * v when it makes sense.
  • In C++20, = default on <=> gives all six comparisons memberwise; == alone gives == and !=. A custom <=> needs a custom == too.
  • Stream <</>> are free functions that return the stream; >> sets failbit on bad input.
  • operator[] (multi-argument since C++23) and operator() must be members; give accessors const overloads.
  • Prefer prefix ++, mark conversion operators explicit, never overload &&, || or ,, and only overload when the meaning is obvious.

Next: Copy Constructors and Copy Assignment, where you'll control what happens when objects are copied.