Legacy C++ › 3. Classes and Object-Oriented Programming
Operator Overloading
Overloading arithmetic, comparison, stream and subscript operators.
intermediate #operator-overloading#friend#stream-operators#subscript
Explanation
You can give most operators meaning for your own types: + - * / == < [] () -> << >> = ++ -- and more. You cannot create new operators or overload . :: ?: sizeof.
Guidelines:
- Make the operator behave like the built-in one; do not surprise users.
- Member operators:
=,[],(),->must be members; compound assignments (+=) are naturally members. - Non-member (often
friend) for symmetric binary operators (a + b,a == b) and for stream operators<</>>since the left operand is the stream. - Implement
+in terms of+=; implement!=,>,<=,>=in terms of==and<. - Prefix
++xreturns a reference; postfixx++takes a dummyintand returns a copy of the old value.
Example
#include <iostream>
class Vec2 {
double x_, y_;
public:
Vec2(double x = 0, double y = 0) : x_(x), y_(y) {}
Vec2& operator+=(const Vec2& o) { x_ += o.x_; y_ += o.y_; return *this; }
double operator[](int i) const { return i == 0 ? x_ : y_; }
Vec2& operator++() { ++x_; ++y_; return *this; } // prefix
Vec2 operator++(int) { Vec2 old(*this); ++*this; return old; } // postfix
friend bool operator==(const Vec2& a, const Vec2& b) { return a.x_ == b.x_ && a.y_ == b.y_; }
friend std::ostream& operator<<(std::ostream& os, const Vec2& v) {
return os << "(" << v.x_ << ", " << v.y_ << ")";
}
};
Vec2 operator+(Vec2 a, const Vec2& b) { return a += b; } // via +=
bool operator!=(const Vec2& a, const Vec2& b) { return !(a == b); }
int main() {
Vec2 a(1, 2), b(3, 4);
Vec2 c = a + b;
std::cout << c << " " << c[0] << " " << (a != b) << "\n"; // (4, 6) 4 1
std::cout << a++ << " " << a << "\n"; // (1, 2) (2, 3)
return 0;
}
Common pitfalls
- A member
operator+makes2.0 + vfail (left operand can’t convert). Make symmetric operators non-members. - Overloading
&&or||loses short-circuiting; overloading,or unary&is almost always a mistake. - Returning a reference from
operator+returns a dangling reference; return by value. - Copy assignment must handle self-assignment and return
*this(see RAII and the Rule of Three). - Define
==and!=(and<with the others) together to stay consistent.
Legacy vs modern
C++20 operator<=> (the spaceship) can generate all six comparison operators from one definition and = default can generate it for you. See Three-way Comparison.
Exercises
1. Why is operator<<(std::ostream&, const T&) not a member of T?
A member operator’s left operand is the object itself, but here the left operand must be the ostream.