Operator Overloading

What Is the Point of Operator Overloading?

Operator overloading makes custom types read like built-in ones, so a + b or cout << value stays clear. Learn the real benefits and the risks of overusing it.

On this page
  1. Code reads like the math it describes
  2. Generic code relies on operators
  3. Where it can go wrong
  4. When it’s worth it
  5. In short

The main point of operator overloading is to let your own types use the same notation as built-in types. Code like a + b or a == b can often be shorter and easier to read than a call to a named function. Operators also plug into library code that expects them, such as the standard algorithms.

Code reads like the math it describes

Compare two ways to add three vectors:

Vec2 total = add(add(a, b), c);   // named functions
Vec2 total = a + b + c;           // operator overloading

The second line is shorter and matches how the sum is usually written. The first is correct too, but the reader has to untangle the nested calls.

Generic code relies on operators

Templates and the standard library use operator syntax, not function names. Once your type defines an operator, library code that uses that operator can work with your type.

For example, std::sort uses < to order elements by default, and std::map and std::set use < to order their keys. A class that defines operator< works with all of them:

#include <algorithm>
#include <vector>

struct Score {
    int points;

    bool operator<(const Score& other) const {
        return points < other.points;
    }
};

int main() {
    std::vector<Score> scores{{30}, {10}, {20}};
    std::sort(scores.begin(), scores.end());  // uses operator<
}

Defining operator<< does the same for output. After that, std::cout << value works for your type.

Where it can go wrong

  • Unclear meanings confuse readers. For two Playlist objects, what a * b should produce isn’t obvious. A named function such as merge says what happens.
  • Hidden costs are easy to miss. A + that returns a new large object may copy data, and that cost can add up inside loops.
  • Implicit conversions can apply in places you didn’t intend. Mark single-argument constructors explicit to prevent unexpected conversions.

When it’s worth it

  • Use it for types where the operator has an obvious meaning, such as vectors, money, fractions, strings, and iterators.
  • Skip it when a named function is clearer.

In short

Operator overloading helps your types fit into existing notation and existing library code. It’s most useful when the operator’s meaning is obvious to anyone who reads the code.

The complete guide to operator overloading

Operator Overloading in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

Enums in C++ With Examples

Learn enums in C++ with clear examples: syntax, automatic values, enum class, switch statements, underlying types, and common mistakes to avoid.

Enums 5 min read