Skip to content

Chapter 19 of 31

Operator Overloading

Create unsurprising value-like operations while preserving established operator semantics.

36 minutes 10 quick checksBy Subha Prasad
Lesson 19 of 31Course navigation

Lesson content

Read, practise, then check your understanding

Operator overloading assigns existing C++ operator syntax to user-defined types. It cannot create new operators or change precedence, associativity, arity, or built-in behavior. At least one operand must be a class or enumeration type.

#include <compare>

class Distance {
    int metres_{};
public:
    explicit Distance(int metres) : metres_{metres} {}

    Distance& operator+=(Distance other) {
        metres_ += other.metres_;
        return *this;
    }

    friend Distance operator+(Distance left, Distance right) {
        left += right;
        return left;
    }

    auto operator<=>(const Distance&) const = default;
};

Implement a mutating compound operator first, then derive its value-returning binary counterpart. The conventional postfix increment takes a dummy int parameter and returns the previous value, while prefix returns the updated object.

Preserve expectations

+ should not secretly modify its operands, equality should be reflexive and consistent, and ordering should support algorithms. Assignment-like operators are normally members; symmetric binary operators often work best as non-members, possibly friends. operator[] commonly supplies const and non-const overloads.

Operators ::, ., .*, and ?: cannot be overloaded. Overloaded && and || do not provide the built-in short-circuit semantics, so avoid them. Use a named function whenever operator meaning would be ambiguous or domain conventions do not make it obvious.

Knowledge check

Answer every question correctly to complete this chapter.

What does operator overloading customize?
Can C++ invent a new operator token?
Which operator should assignment usually return?
Why implement symmetric binary operators as non-members?
Should overloaded operators preserve expected meaning?
Which operators cannot be overloaded?
Can overloading change operator precedence?
How is postfix increment distinguished?
What should operator== represent?
When should an operator overload be avoided?

0 of 10 checks passed

Your progress is saved on this device.