Operator overloading in C++

Difficulty: Intermediate

Question

How does operator overloading work in C++? Show how to overload +, ==, <<, and prefix/postfix ++, and explain member vs non-member overloads.

Answer

Operator overloading lets your own types behave like built-ins, so that a Vector2 can be added with + and a Fraction compared with ==. Used well, it makes code read like mathematics. Used badly, it makes code baffling. Let's see the mechanics and the judgement.

An operator is just a function with a special name, like operator+. 'a + b' is turned by the compiler into either a.operator+(b) (member) or operator+(a, b) (free function). You cannot invent new operators or change precedence and arity, and a few cannot be overloaded at all: the scope resolution ::, member access ., .*, the ternary ?:, and sizeof.

Member or non-member? A sound guideline: operators that modify their left operand or must be members (=, [], (), ->) go inside the class; operators that are symmetric (+, -, ==, <) are best as free functions, often implemented in terms of a compound-assignment member like +=. The reason is implicit conversions: with a free function operator+(Vec, Vec) and an implicit constructor from a scalar, both '2 + v' and 'v + 2' can work, while a member function only allows conversion on the right-hand side. The stream operators << and >> must be free functions, since their left operand is the stream, not your class. If they need private data, declare them as friends.

Prefix versus postfix increment is a favourite. Prefix ++x is declared as T& operator++() and returns a reference to the modified object. Postfix x++ has a dummy int parameter, T operator++(int), and returns a copy of the old value. Because postfix must make that copy, prefer ++i for iterators and user-defined types in loops.

For comparisons, C++20 improved life: define operator<=> (the spaceship operator) with = default and the compiler generates <, >, <=, >=, and if you also default operator==, the equality operators too. In earlier standards you write == and < by hand and derive the rest.

Some practical rules of taste. Keep semantics unsurprising: + should not mutate its operands, and == should be an equivalence relation. Return by const reference or value as appropriate. Avoid overloading && and || (they lose short-circuit behaviour) and the comma operator. Do not overload operators just because you can; for anything without an obvious, natural meaning, a named function is clearer. The = operator ties back to the rule of three/five, since any type that owns resources needs a proper copy assignment.

In an interview, be ready to write a small Vector2 or Fraction class with +, ==, <<, and both increments, and to explain why << is not a member.

Code examples

A Vec2 with common operators

#include <iostream>

class Vec2 {
    int x_, y_;
public:
    Vec2(int x = 0, int y = 0) : x_(x), y_(y) {}

    Vec2& operator+=(const Vec2& o) { x_ += o.x_; y_ += o.y_; return *this; }
    Vec2& operator++()    { ++x_; ++y_; return *this; }        // prefix
    Vec2  operator++(int) { Vec2 old = *this; ++*this; return old; }  // postfix

    friend Vec2 operator+(Vec2 a, const Vec2& b) { return a += b; }
    friend bool operator==(const Vec2& a, const Vec2& b) { return a.x_ == b.x_ && a.y_ == b.y_; }
    friend std::ostream& operator<<(std::ostream& os, const Vec2& v) {
        return os << "(" << v.x_ << ", " << v.y_ << ")";
    }
};

int main() {
    Vec2 a(1, 2), b(3, 4);
    std::cout << a + b << "\n";
    std::cout << (a == Vec2(1, 2)) << "\n";
    std::cout << a++ << " " << a << "\n";   // postfix returns old value
    std::cout << ++a << "\n";               // prefix returns new value
}

operator+ is a non-member (friend) built on the member +=. Postfix ++ returns a copy of the old value; prefix returns the updated object.

Key points

Common follow-up questions

Interview tips

Concepts covered

operator overloading, member vs non-member, prefix vs postfix, stream operators

More C++ & STL questions