# Operator overloading in C++

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

Canonical: https://www.internhack.in/learn/interview/cpp-interview/cpp-operator-overloading
Last updated: 2026-11-28

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

- An operator is a function named operatorX; a + b becomes a.operator+(b) or operator+(a, b).
- =, \[\], () and -> must be members; << and >> for streams must be free functions.
- Prefix ++ returns T&; postfix ++ takes a dummy int and returns a copy.
- Build binary operators on compound assignment (+ from +=).
- C++20's defaulted operator<=> generates all the comparison operators.

## Common follow-up questions

- Why can't you overload the scope resolution operator?
- Why should you avoid overloading && and ||?
- How does the spaceship operator simplify comparisons?

## Interview tips

- Be ready to code a small class with +, ==, << on a whiteboard.
- Explain why postfix increment is less efficient than prefix.

## Concepts covered

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

Previous: [Function overloading vs overriding (and name hiding)](https://www.internhack.in/learn/interview/cpp-interview/cpp-overloading-vs-overriding) · Next: [Friend functions and inline functions](https://www.internhack.in/learn/interview/cpp-interview/cpp-friend-inline-functions) · [All of C++ & STL](https://www.internhack.in/learn/interview/cpp-interview)

## More C++ & STL questions

- [Templates and template specialization](https://www.internhack.in/learn/interview/cpp-interview/cpp-templates-specialization)
- [Smart pointers: unique_ptr and shared_ptr](https://www.internhack.in/learn/interview/cpp-interview/cpp-smart-pointers)
- [weak_ptr and breaking shared_ptr cycles](https://www.internhack.in/learn/interview/cpp-interview/cpp-weak-ptr-circular-references)
- [vector growth and iterator invalidation](https://www.internhack.in/learn/interview/cpp-interview/cpp-vector-growth-iterator-invalidation)
- [map vs unordered_map, and choosing an STL container](https://www.internhack.in/learn/interview/cpp-interview/cpp-map-vs-unordered-map-containers)
- [STL algorithms and priority_queue: sort, lower_bound, heaps](https://www.internhack.in/learn/interview/cpp-interview/cpp-stl-algorithms-priority-queue)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [C++ & STL](https://www.internhack.in/learn/interview/cpp-interview)
