Operator overloading is why std::string + std::string concatenates and why std::cout << 42 prints — the standard library is built on it, and unit 8 is unusable without it. It exists so that user-defined types can join the same expression syntax as built-in ones; without it, math-heavy code degenerates into add(mul(a, b), c).
Operators are functions
In C++, a + b on your own type can be made to work by defining a function named operator+. This is operator overloading, the same overloading idea from lesson 4-3, applied to symbols:
struct Vec2 { double x, y; Vec2(double px, double py) : x(px), y(py) {} Vec2 operator+(const Vec2& rhs) const { return Vec2(x + rhs.x, y + rhs.y); } bool operator==(const Vec2& rhs) const { return x == rhs.x && y == rhs.y; } }; Vec2 c = a + b; // calls a.operator+(b)
Note the parameter is a const Vec2& (lesson 4-2's cheap read-only pass) and the method is const (lesson 7-2). The pieces you have learned compose.
Printing your type: operator<<
std::cout << v needs an operator whose LEFT side is the stream, so it is written as a free function outside the class:
std::ostream& operator<<(std::ostream& os, const Vec2& v) { return os << "(" << v.x << ", " << v.y << ")"; }
Returning the stream is what lets << chain. Overload only when the meaning is obvious (math types, comparisons). + meaning "launch missiles" compiles, and gets you banned from code review.
Code exercise · cpp
Run this. Vec2 now adds with + and prints with << like a built-in type.
Quiz
Why is operator<< for your class written as a free function instead of a method of the class?
Code exercise · cpp
Your turn. Add operator- (subtract componentwise) and operator== to Vec2. Expected output: `(2, 2)` then `equal: false`.