Skip to content

Operator Overloading

Learn how to overload operators correctly — member vs non-member, canonical forms, stream operators, the C++20 spaceship operator, and common pitfalls.

Operator Overloading Philosophy

C++ lets you define how operators (+, ==, <<, [], etc.) work for your own types. The golden rule: do what the ints do. Overloaded operators should behave as users expect from built-in types. If a + b modifies a, you have violated user expectations.

Operator overloading is what makes types like std::string, std::vector, and std::complex feel natural. But used poorly, it creates confusing, unmaintainable code. Never overload operators to do something surprising.

Member vs Non-Member Operators

Some operators must be members (=, [], ->, ()). Others are better as non-members (especially binary operators like + and ==) to allow symmetric conversions. The canonical pattern: implement += as a member, then + as a non-member using +=.

operators.cpp
#include <iostream>

class Vec2 {
    double x_, y_;

public:
    Vec2(double x = 0, double y = 0) : x_{x}, y_{y} {}

    // += is a member: modifies *this
    Vec2& operator+=(const Vec2& rhs) {
        x_ += rhs.x_;
        y_ += rhs.y_;
        return *this;
    }

    // Unary minus (member)
    Vec2 operator-() const {
        return Vec2{-x_, -y_};
    }

    // Accessors for non-member operators
    double x() const { return x_; }
    double y() const { return y_; }

    // [] operator (must be member)
    double& operator[](int i) {
        return i == 0 ? x_ : y_;
    }
    const double& operator[](int i) const {
        return i == 0 ? x_ : y_;
    }
};

// + is a non-member using +=  (canonical form)
Vec2 operator+(Vec2 lhs, const Vec2& rhs) {  // lhs by value!
    lhs += rhs;
    return lhs;
}

// == as non-member (symmetric: allows conversions on both sides)
bool operator==(const Vec2& a, const Vec2& b) {
    return a.x() == b.x() && a.y() == b.y();
}

// Stream output operator (must be non-member)
std::ostream& operator<<(std::ostream& os, const Vec2& v) {
    return os << '(' << v.x() << ", " << v.y() << ')';
}

int main() {
    Vec2 a{1.0, 2.0}, b{3.0, 4.0};
    Vec2 c = a + b;           // uses non-member operator+
    std::cout << c << '\n';   // (4, 6)
    std::cout << -c << '\n';  // (-4, -6)
    std::cout << c[0] << '\n'; // 4
    std::cout << std::boolalpha << (a == b) << '\n'; // false
    return 0;
}

C++20 Spaceship Operator (<=>)

C++20 introduces the three-way comparison operator <=> (the "spaceship operator"). A single operator<=> definition auto-generates all six comparison operators (<, >, <=, >=, ==, !=). Use = default when member-wise comparison is what you want.

spaceship.cpp
#include <iostream>
#include <compare>
#include <string>

class Version {
    int major_;
    int minor_;
    int patch_;

public:
    Version(int major, int minor, int patch)
        : major_{major}, minor_{minor}, patch_{patch} {}

    // Defaulted <=>: compares members in declaration order
    auto operator<=>(const Version&) const = default;

    friend std::ostream& operator<<(std::ostream& os, const Version& v) {
        return os << v.major_ << '.' << v.minor_ << '.' << v.patch_;
    }
};

class Student {
    std::string name_;
    double gpa_;

public:
    Student(const std::string& name, double gpa)
        : name_{name}, gpa_{gpa} {}

    // Custom <=>: compare only by GPA
    auto operator<=>(const Student& other) const {
        return gpa_ <=> other.gpa_;
    }

    // Need separate == if <=> is not defaulted
    bool operator==(const Student& other) const {
        return gpa_ == other.gpa_;
    }

    friend std::ostream& operator<<(std::ostream& os, const Student& s) {
        return os << s.name_ << " (GPA: " << s.gpa_ << ')';
    }
};

int main() {
    Version v1{2, 0, 0}, v2{1, 9, 5};
    std::cout << v1 << " > " << v2 << "? "
              << std::boolalpha << (v1 > v2) << '\n';  // true
    std::cout << (v1 == v2) << '\n';  // false

    Student alice{"Alice", 3.9};
    Student bob{"Bob", 3.7};
    std::cout << (alice > bob) << '\n';  // true (higher GPA)
    return 0;
}

operator() — Function Objects

Overloading operator() creates a functor (function object). Functors can hold state, making them more flexible than plain function pointers. They are used extensively with STL algorithms.

functor.cpp
#include <iostream>
#include <vector>
#include <algorithm>

// A functor that counts how many times it's called
class Counter {
    int count_ = 0;
    int threshold_;

public:
    explicit Counter(int threshold) : threshold_{threshold} {}

    bool operator()(int value) {
        ++count_;
        return value > threshold_;
    }

    int calls() const { return count_; }
};

int main() {
    std::vector<int> nums{1, 5, 3, 8, 2, 9, 4, 7, 6};

    Counter above_five{5};
    auto count = std::count_if(nums.begin(), nums.end(), above_five);
    std::cout << count << " elements above 5\n";  // 4

    // Functors can also be used directly
    Counter is_positive{0};
    std::cout << std::boolalpha;
    std::cout << is_positive(42) << '\n';   // true
    std::cout << is_positive(-1) << '\n';   // false
    std::cout << "Calls: " << is_positive.calls() << '\n';  // 2

    return 0;
}
Pitfall

Do not overload operators to do surprising things. operator+ should add, not subtract. operator* on a Matrix should do matrix multiplication, not element-wise multiplication (unless that is what your domain expects). Some operators cannot be overloaded: ::, ., .*, ?:, and sizeof. Also, overloading && and || loses short-circuit evaluation — almost never a good idea.

Best Practice

Follow canonical forms: implement compound assignment (+=, -=) as members, then define binary operators (+, -) as non-members using the compound version. Always implement operator== if you implement operator< (or better, use C++20 <=> to get all six). Implement stream operators (<<, >>) as non-member friends. Use explicit on conversion operators to prevent accidental implicit conversions.

Key Takeaways
  • Follow the "do what the ints do" principle — operators should behave as users expect
  • Implement compound assignment (+=) as a member, then + as a non-member using +=
  • C++20's operator<=> generates all six comparison operators from a single definition
  • Overloading operator() creates functors — objects that can be called like functions
  • &&, || lose short-circuit evaluation when overloaded — avoid overloading them
  • Some operators cannot be overloaded: ::, ., .*, ?:, sizeof

Quiz — Test Your Knowledge

(15 XP)

1. Why is `operator+` typically implemented as a non-member function?

2. What does `auto operator<=>(const T&) const = default;` do in C++20?

3. Why should you avoid overloading `operator&&` and `operator||`?