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
Playlistobjects, whata * bshould produce isn’t obvious. A named function such asmergesays 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
explicitto 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.