Modern C++ • C++20 baseline
Operator Overloading and Regular Types
Overload operators only when they preserve familiar meaning for the type.
Operators can make domain types feel natural, but surprising overloads make APIs harder to learn. Keep symmetry, return types, and mutation semantics close to standard expectations. Prefer non-member operators when conversions on both operands are useful, and do not overload operators merely to save a function name.
Key points
- Equality should reflect the type’s value semantics.
- A mutating compound operator commonly returns a reference to the current object.
Example
struct Point {
int x{};
int y{};
friend Point operator+(Point left, const Point& right) {
left.x += right.x;
left.y += right.y;
return left;
}
};
What to expect
Point{1, 2} + Point{3, 4} produces Point{4, 6}.
Practice exercise
Add equality for Point and define whether two points compare by coordinates or identity.
Key idea: An overloaded operator should be predictable from the operation’s established meaning.