← C++ roadmap

Topic 10 of 27 · Advanced

Operator Overloading

Custom operators, comparisons and the spaceship operator.

Concept

Operators can be overloaded for user types so they read naturally: a + b, cout << obj, a < b.

Arithmetic operators usually return a new object; compound ones (+=) return *this by reference. Stream operators are non-member friends.

C++20's operator<=> generates all comparison operators at once with = default.

Code (C++20)

#include <compare>
#include <iostream>

struct Money {
    long paise;
    Money operator+(const Money& o) const { return {paise + o.paise}; }
    Money& operator+=(const Money& o) { paise += o.paise; return *this; }
    auto operator<=>(const Money&) const = default;
    friend std::ostream& operator<<(std::ostream& os, const Money& m) {
        return os << "Rs " << m.paise / 100 << '.' << m.paise % 100;
    }
};

int main() {
    Money a{1050}, b{299};
    std::cout << a + b << ' ' << (a > b) << '\n';
}

Remember

  • Keep operator meaning intuitive.
  • << and >> are non-member functions.
  • Use <=> = default for comparisons.

Interview questions

Which operators can't be overloaded?

:: (scope), . (member access), .* , ?: (ternary), sizeof and typeid.

Why return a reference from operator=?

To allow chaining (a = b = c) and avoid an unnecessary copy.

Practise C++ with the AI mentor

Lesson test

Take an 8-question test on “Operator Overloading” — concepts, output prediction, bug spotting and interview questions.

Can't find a C++ topic you need for exams or placements? Request it and we'll add it.