Operator Overloading

Does C++ Allow Operator Overloading?

Yes, C++ allows operator overloading for your own types. Here is how it compares with C, Java, C#, and Python, and where the feature has limits.

On this page
  1. What C++ lets you do
  2. What C++ doesn’t let you do
  3. How other languages compare
  4. Should you use it?
  5. In short

Yes. C++ allows operator overloading for your own classes and enumerations. You can define +, ==, <<, and most other operators for a type you create. C++ doesn’t let you change how operators work on built-in types such as int, though, and a few operators can’t be overloaded at all.

What C++ lets you do

You define an operator by writing a function whose name is operator followed by the symbol:

struct Money {
    long cents;
};

Money operator+(const Money& a, const Money& b) {
    return Money{a.cents + b.cents};
}

int main() {
    Money total = Money{250} + Money{199};  // calls operator+
}

The compiler uses this function because one of the operands is a Money.

What C++ doesn’t let you do

  • Change how int + int or other built-in operations work.
  • Invent new operator symbols.
  • Change an operator’s precedence, associativity, or number of operands.
  • Overload ::, ., .*, ?:, sizeof, or typeid.

The answer to which operators cannot be overloaded is a short list: ::, ., .*, and ?:, plus sizeof and typeid.

How other languages compare

  • C has no operator overloading. Its operators work only on built-in types.
  • Java doesn’t let you overload operators for your own classes. The + operator works on String because the language builds that in.
  • C# supports operator overloading with the operator keyword on static methods, much like C++.
  • Python has no operator keyword. A class defines special methods such as __add__ to handle +.

Should you use it?

Operator overloading is allowed, but that doesn’t make it the right choice every time. Use it when the operator has an obvious meaning for your type, such as vector math. Prefer a named function when the meaning isn’t clear.

In short

Yes, C++ allows operator overloading for your own types. It doesn’t let you change built-in operators, invent new symbols, or overload a handful of operators such as :: and ..

The complete guide to operator overloading

Operator Overloading in C++
Read the guide

Keep exploring

Guides from other topics

All topics →