Operator overloading
Operator overloading lets a class define what +, ==, [], << and other operators mean for its objects. The call a + b becomes operator+(a, b) or a.operator+(b). Precedence does not change.
Detailed Explanation
std::string concatenates with +. std::vector indexes with []. std::cout prints with <<. None of those are built-in on the class; they are overloaded operators. The feature exists so user types can look like the types the language already has, when the meaning is the same idea: add, compare, index, stream.
You may overload most operators. You may not invent new symbols. You may not change arity, precedence, or associativity. You cannot overload ::, ., .*, or the ternary ?:. operator new and operator delete are overloadable and are a different topic (allocation).
Two implementation homes:
Member. T operator+(const T& other) const. The left operand is *this. Members are required for =, [], (), ->. They are natural for mutating operators (+=).
Non-member. T operator+(T a, const T& b). Needed when the left operand is not your type (2 * money if Money * int exists) or when you want implicit conversions on both sides. Stream insertion is always a non-member: std::ostream& operator<<(std::ostream&, const T&), often a friend so it can read private fields.
Rules of taste, which are also rules of survival:
- Overload an operator only when its meaning is obvious from the built-in.
+for money or matrices. Not+for "register a listener". - If you provide
==, provide!=(C++20operator==can generate!=; C++20operator<=>can generate the rest of the comparisons). - If you provide
+, provide+=, and implement+in terms of+=on a copy so you write the logic once. operator[]should come in const and non-const pairs, likevector.operator boolshould beexplicitsostring + userdoes not convert the user to bool and then to int.- Do not overload
&&,||, or,. Overloading them loses short-circuit and sequencing that callers assume.
Return types follow the built-ins. + returns a new value. += returns T&. ++ prefix returns T&; postfix T operator++(int) returns the old value by value (the int is a dummy the compiler passes to distinguish the two). [] returns a reference to the element.
A conversion operator (operator int() const) is an overload too. explicit conversions only run when the target type is written. Implicit ones participate in every overload resolution and create the worst ambiguities in the language.
Code Examples
#include <iostream>
#include <ostream>
class Cents {
public:
explicit Cents(int n) : n_(n) {}
Cents& operator+=(Cents other) {
n_ += other.n_;
return *this;
}
int value() const { return n_; }
private:
int n_;
friend Cents operator+(Cents a, Cents b);
friend std::ostream& operator<<(std::ostream& os, Cents c);
};
Cents operator+(Cents a, Cents b) {
a += b;
return a;
}
std::ostream& operator<<(std::ostream& os, Cents c) {
return os << c.n_ << "c";
}
int main() {
Cents a{40};
Cents b{5};
std::cout << (a + b) << '\n'; // prints: 45c
}#include <cassert>
#include <cstddef>
#include <vector>
struct Row {
std::vector<int> cells;
int& operator[](std::size_t i) { return cells.at(i); }
const int& operator[](std::size_t i) const { return cells.at(i); }
};
int main() {
Row r{{1, 2, 3}};
r[1] = 9;
assert(r[1] == 9);
}Common Gotchas
`operator bool` without `explicit`
the object becomes an `int` in arithmetic. Write `explicit operator bool() const`.
`operator+` as a member blocks `2 + money`
the left operand cannot convert into `*this` for built-in `2`. Provide a non-member.
Overloading `&&` disables short-circuit
both sides are always evaluated. Do not do it.
`operator[]` does not have to be bounds-checked
`vector::operator[]` is unchecked; `at` throws. Pick one policy and document it. The example above uses `at` so a bad index is defined.