Operator overloading in C++ lets you define what operators such as +, ==, and << do for your own types. Once + is defined for a Vec2 or Money class, an expression like a + b reads the same way it does for int and double. Under the hood, an overloaded operator is an ordinary function with a special name, so the compiler calls it the way it calls any other function.
How operator overloading works
You overload an operator by writing a function whose name is the keyword operator followed by the operator symbol. The compiler calls that function when one of the operands has your type:
a + bcallsoperator+.a == bcallsoperator==.std::cout << vcallsoperator<<whenvis your type.
There are two forms:
- Member function. The left operand is the object the function is called on, so
a + bcan meana.operator+(b). - Non-member function. Both operands are parameters. You need this form when the left operand is not your type.
A complete example
The program below gives a Vec2 struct three operators and a stream output operator.
#include <iostream>
struct Vec2 {
double x;
double y;
Vec2 operator+(const Vec2& other) const {
return {x + other.x, y + other.y};
}
Vec2& operator+=(const Vec2& other) {
x += other.x;
y += other.y;
return *this;
}
bool operator==(const Vec2& other) const {
return x == other.x && y == other.y;
}
};
std::ostream& operator<<(std::ostream& out, const Vec2& v) {
return out << "(" << v.x << ", " << v.y << ")";
}
int main() {
Vec2 a{1.0, 2.0};
Vec2 b{3.0, 4.0};
Vec2 c = a + b; // calls a.operator+(b)
c += a; // calls c.operator+=(a)
std::cout << c << "\n"; // prints (5, 8)
std::cout << (a == b) << "\n"; // prints 0, because the vectors differ
}
Output:
(5, 8)
0
Here is what each part does:
operator+is a member that returns a newVec2. Its argument is aconstreference, so no copy is made, and the function is markedconstbecause it doesn’t change either operand.operator+=changes the left operand, so it returnsVec2&. Returning a reference lets you chain calls such asa += b += c.operator==returnsbool, the same as the built-in comparisons.operator<<is a non-member because its left operand is astd::ostream, which isn’t your type. It returns the stream so output can be chained.
Member or non-member?
Use these rules of thumb:
- Make it a member when the left operand is your type and the operator belongs to the object, such as
+=. The operators=,[],(), and->must be members. - Make it a non-member when the left operand is a different type. For example,
2.0 * vneeds a non-member that takes thedoublefirst:
Vec2 operator*(double scale, const Vec2& v) {
return {v.x * scale, v.y * scale};
}
- Declare a non-member as a
friendinside the class when it needs private members.
If you define v * 2.0 as a member, define the 2.0 * v form as well, so both orders work.
Which operators you can and cannot overload
Most operators can be overloaded, including arithmetic, comparison, assignment, subscript [], call (), dereference *, arrow ->, increment ++, and the stream operators << and >>.
A few rules apply to all of them:
- At least one operand must be a class type or an enumeration. You can’t change how
int + intworks. - You can’t create new operator symbols. C++ has no
**operator, and you can’t add one. - Precedence, associativity, and the number of operands stay the same.
%is always binary, and!is always unary. =,[],(), and->must be non-static member functions.
If you wonder which operators cannot be overloaded, the answer is a short, fixed list: ::, ., .*, and ?:. The sizeof and typeid operators can’t be overloaded either.
Return types and conventions
The return type tells the reader what the operator produces, so choose it carefully:
- Binary operators such as
+usually return a new object by value and leave their operands unchanged. - Compound assignments such as
+=returnT&, so chaining works. <<returnsstd::ostream&, and>>returnsstd::istream&.- Comparisons return
bool. - Prefix
++returns a reference to the changed object. Postfix++takes an unnamedintthat only marks the postfix form, and returns the old value.
class Counter {
public:
Counter& operator++() { // prefix: ++c
++value_;
return *this;
}
Counter operator++(int) { // postfix: c++, the int only marks this form
Counter old = *this;
++value_;
return old;
}
private:
int value_ = 0;
};
Common pitfalls
- Overloaded
&&and||lose short-circuit evaluation. The built-in versions skip the right side when the left side decides the result. An overloaded version is a function call, so both operands are evaluated before it runs. - Don’t change an operator’s meaning.
+should add, and<<should write output. Surprising meanings make code harder to read and maintain. - Keep related operators consistent. If you define
==, define!=as well. If you define+=, you can write+in terms of it. - Watch for implicit conversions. A constructor that takes one argument lets the compiler convert values to your type without being asked. Mark it
explicitto prevent that. - Handle self-assignment in
operator=. Check forthis == &otherbefore you release or copy resources.
Operator overloading in the standard library
The standard library uses the same mechanism:
std::stringoverloads+for concatenation, and==and<for comparison.std::complexsupports arithmetic operators for complex numbers.- Iterators overload
*,++, and!=, so loops and algorithms can step through containers in the same way. - Smart pointers such as
std::unique_ptroverload*and->, so they can be used much like raw pointers. std::sort,std::map, andstd::setuse<by default, so a type that definesoperator<works with them.
When to avoid it
Operator overloading fits best when an operator has an obvious meaning for your type, such as vector math, money amounts, or string-like values. It fits poorly when the meaning is unclear. For a Database class, db + record is hard to read, while db.insert(record) says what happens.
Key points
- Operator overloading defines operators for your own types through
operatorfunctions. - Use a member function for operators that belong to the object, and a non-member when the left operand is a different type or for
<<. - Some operators can’t be overloaded, and you can’t invent new ones.
- Keep meanings intuitive, and watch for lost short-circuit evaluation and implicit conversions.