C++C++ Explainer
C++ · 2 · Classes & RAII10 / 36 · 28%

Operator Overloading

Give your types natural syntax — without surprising the reader.

Examples: operator+, operator==, operator<<

shortcuts: ← prev · → next · M mark
1

Arithmetic Operators

Implement += as a member, then + as a non-member built on it.

Example
example
struct Vec2 {
    float x{}, y{};
    Vec2& operator+=(const Vec2& r) { x += r.x; y += r.y; return *this; }
};

inline Vec2 operator+(Vec2 l, const Vec2& r) { l += r; return l; }
2

Comparison (C++20)

One spaceship operator generates all six comparisons.

Example
example
struct Version {
    int major, minor, patch;
    auto operator<=>(const Version&) const = default;
    bool operator==(const Version&) const = default;
};

Version{1,2,0} < Version{1,10,0};   // true
3

Stream Insertion

Must be a non-member, because the left operand is the stream.

Example
example
std::ostream& operator<<(std::ostream& os, const Vec2& v) {
    return os << '(' << v.x << ", " << v.y << ')';
}

std::cout << Vec2{1,2} << '\n';   // (1, 2)
4

Rules of Taste

Overloading is easy to abuse.

Common pitfalls
  • ✕Only overload when the meaning is obvious (+ on a vector, not on a Logger).
  • ✕Keep operator semantics conventional: + must not modify its operands.
  • ✕operator[] should return a reference so callers can assign through it.
  • ✕Overload == and != consistently, or use = default with <=>.