Operator Overloading
Prerequisites: Static members
C++ lets a class define what an existing operator (+, ==, <<,
and others) means for its own type:
class Point {
public:
int x, y;
Point(int x, int y) : x(x), y(y) {}
Point operator+(const Point &other) const {
return Point(x + other.x, y + other.y);
}
};
Point a(1, 2), b(3, 4);
Point c = a + b; // calls operator+ — c is (4, 6)
Overloading operator<< is how a class becomes printable directly
with std::cout:
std::ostream &operator<<(std::ostream &os, const Point &p) {
os << "(" << p.x << ", " << p.y << ")";
return os;
}
std::cout << c << std::endl; // (4, 6)
Common mistakes
- Overloading an operator to do something that surprises a reader
(e.g.
+that doesn't behave anything like addition) — overload only when the operator's usual meaning genuinely fits.