Operator Overloading

Operator Overloading in C++

Learn how operator overloading works in C++: syntax, a full example, member vs. non-member rules, operators you can't overload, and pitfalls.

On this page
  1. How operator overloading works
  2. A complete example
  3. Member or non-member?
  4. Which operators you can and cannot overload
  5. Return types and conventions
  6. Common pitfalls
  7. Operator overloading in the standard library
  8. When to avoid it
  9. Key points

Operator overloading in C++ lets you define what operators such as +, ==, and << do for your own types. Once + is defined for a Vec2 or Money class, an expression like a + b reads the same way it does for int and double. Under the hood, an overloaded operator is an ordinary function with a special name, so the compiler calls it the way it calls any other function.

How operator overloading works

You overload an operator by writing a function whose name is the keyword operator followed by the operator symbol. The compiler calls that function when one of the operands has your type:

  • a + b calls operator+.
  • a == b calls operator==.
  • std::cout << v calls operator<< when v is your type.

There are two forms:

  • Member function. The left operand is the object the function is called on, so a + b can mean a.operator+(b).
  • Non-member function. Both operands are parameters. You need this form when the left operand is not your type.

A complete example

The program below gives a Vec2 struct three operators and a stream output operator.

#include <iostream>

struct Vec2 {
    double x;
    double y;

    Vec2 operator+(const Vec2& other) const {
        return {x + other.x, y + other.y};
    }

    Vec2& operator+=(const Vec2& other) {
        x += other.x;
        y += other.y;
        return *this;
    }

    bool operator==(const Vec2& other) const {
        return x == other.x && y == other.y;
    }
};

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

int main() {
    Vec2 a{1.0, 2.0};
    Vec2 b{3.0, 4.0};

    Vec2 c = a + b;         // calls a.operator+(b)
    c += a;                 // calls c.operator+=(a)

    std::cout << c << "\n";          // prints (5, 8)
    std::cout << (a == b) << "\n";   // prints 0, because the vectors differ
}

Output:

(5, 8)
0

Here is what each part does:

  • operator+ is a member that returns a new Vec2. Its argument is a const reference, so no copy is made, and the function is marked const because it doesn’t change either operand.
  • operator+= changes the left operand, so it returns Vec2&. Returning a reference lets you chain calls such as a += b += c.
  • operator== returns bool, the same as the built-in comparisons.
  • operator<< is a non-member because its left operand is a std::ostream, which isn’t your type. It returns the stream so output can be chained.

Member or non-member?

Use these rules of thumb:

  • Make it a member when the left operand is your type and the operator belongs to the object, such as +=. The operators =, [], (), and -> must be members.
  • Make it a non-member when the left operand is a different type. For example, 2.0 * v needs a non-member that takes the double first:
Vec2 operator*(double scale, const Vec2& v) {
    return {v.x * scale, v.y * scale};
}
  • Declare a non-member as a friend inside the class when it needs private members.

If you define v * 2.0 as a member, define the 2.0 * v form as well, so both orders work.

Which operators you can and cannot overload

Most operators can be overloaded, including arithmetic, comparison, assignment, subscript [], call (), dereference *, arrow ->, increment ++, and the stream operators << and >>.

A few rules apply to all of them:

  • At least one operand must be a class type or an enumeration. You can’t change how int + int works.
  • You can’t create new operator symbols. C++ has no ** operator, and you can’t add one.
  • Precedence, associativity, and the number of operands stay the same. % is always binary, and ! is always unary.
  • =, [], (), and -> must be non-static member functions.

If you wonder which operators cannot be overloaded, the answer is a short, fixed list: ::, ., .*, and ?:. The sizeof and typeid operators can’t be overloaded either.

Return types and conventions

The return type tells the reader what the operator produces, so choose it carefully:

  • Binary operators such as + usually return a new object by value and leave their operands unchanged.
  • Compound assignments such as += return T&, so chaining works.
  • << returns std::ostream&, and >> returns std::istream&.
  • Comparisons return bool.
  • Prefix ++ returns a reference to the changed object. Postfix ++ takes an unnamed int that only marks the postfix form, and returns the old value.
class Counter {
public:
    Counter& operator++() {       // prefix: ++c
        ++value_;
        return *this;
    }

    Counter operator++(int) {     // postfix: c++, the int only marks this form
        Counter old = *this;
        ++value_;
        return old;
    }

private:
    int value_ = 0;
};

Common pitfalls

  • Overloaded && and || lose short-circuit evaluation. The built-in versions skip the right side when the left side decides the result. An overloaded version is a function call, so both operands are evaluated before it runs.
  • Don’t change an operator’s meaning. + should add, and << should write output. Surprising meanings make code harder to read and maintain.
  • Keep related operators consistent. If you define ==, define != as well. If you define +=, you can write + in terms of it.
  • Watch for implicit conversions. A constructor that takes one argument lets the compiler convert values to your type without being asked. Mark it explicit to prevent that.
  • Handle self-assignment in operator=. Check for this == &other before you release or copy resources.

Operator overloading in the standard library

The standard library uses the same mechanism:

  • std::string overloads + for concatenation, and == and < for comparison.
  • std::complex supports arithmetic operators for complex numbers.
  • Iterators overload *, ++, and !=, so loops and algorithms can step through containers in the same way.
  • Smart pointers such as std::unique_ptr overload * and ->, so they can be used much like raw pointers.
  • std::sort, std::map, and std::set use < by default, so a type that defines operator< works with them.

When to avoid it

Operator overloading fits best when an operator has an obvious meaning for your type, such as vector math, money amounts, or string-like values. It fits poorly when the meaning is unclear. For a Database class, db + record is hard to read, while db.insert(record) says what happens.

Key points

  • Operator overloading defines operators for your own types through operator functions.
  • Use a member function for operators that belong to the object, and a non-member when the left operand is a different type or for <<.
  • Some operators can’t be overloaded, and you can’t invent new ones.
  • Keep meanings intuitive, and watch for lost short-circuit evaluation and implicit conversions.

Keep exploring

Guides from other topics

All topics →