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 + intor other built-in operations work. - Invent new operator symbols.
- Change an operator’s precedence, associativity, or number of operands.
- Overload
::,.,.*,?:,sizeof, ortypeid.
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 onStringbecause the language builds that in. - C# supports operator overloading with the
operatorkeyword onstaticmethods, much like C++. - Python has no
operatorkeyword. 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 ..