Skip to content

Operator Overloading

Operator overloading allows you to define how standard operators (like +, -, <<) work with your custom classes. This makes your types behave like built-in types.

Basic Syntax

You define a function with the name operator@, where @ is the symbol.

class Vector2D {
public:
    float x, y;

    Vector2D(float x, float y) : x(x), y(y) {}

    // Overload + operator
    Vector2D operator+(const Vector2D& other) const {
        return Vector2D(x + other.x, y + other.y);
    }
};

Vector2D v1(1, 2);
Vector2D v2(3, 4);
Vector2D v3 = v1 + v2; // Calls v1.operator+(v2)

Friend Functions for Overloading

Sometimes you need to overload an operator where the left-hand side is not your class (e.g., std::cout << obj).

class Person {
    std::string name;
public:
    Person(std::string n) : name(n) {}

    // Friend declaration allows access to private members
    friend std::ostream& operator<<(std::ostream& os, const Person& p);
};

// Definition outside class
std::ostream& operator<<(std::ostream& os, const Person& p) {
    os << "Person(" << p.name << ")";
    return os;
}

// Usage
Person p("Alice");
std::cout << p << "\n";

Common Operators to Overload

  • Arithmetic: +, -, *, /
  • Comparison: ==, !=, <, > (Or <=> in C++20)
  • Stream Insertion: << (for printing)
  • Subscript: [] (for array-like access)
  • Function Call: () (Functors)

The Spaceship Operator (<=>) (C++20)

In C++20, you can default the three-way comparison operator to automatically generate all comparison operators.

1
2
3
4
5
6
7
#include <compare>

class Version {
    int major, minor, patch;
public:
    auto operator<=>(const Version&) const = default;
};