Operator Overloading
You already know how to write a + b with integers, or s1 == s2 with strings, or cout << x to print something, right? For built-in types, C++ already knows what all these operators mean. But what about YOUR custom classes? Like, what does it mean to "add" two Vector2 objects together? Or to "print" a Fraction? The compiler has absolutely no idea — unless you tell it. And that's what operator overloading is all about.
Here's the cool part: when you write a + b, the compiler is actually translating that into a function call behind the scenes — either a.operator+(b) (if it's a member function) or operator+(a, b) (if it's a non-member/friend function). So operator overloading is really just syntactic sugar — a fancy way to call a function that makes your classes feel as natural to use as int or string.
This week you'll learn the two ways to overload operators: member functions (where the left operand is this, the object itself) and friend functions (where both operands are parameters, and the function gets access to private members). Some operators, like << for printing, MUST be done as friend functions because the left operand is ostream, not your class.
| Operator Category | Examples | Typical Implementation |
|---|---|---|
| Arithmetic | +, -, *, / | Member function: T operator+(const T& other) const |
| Comparison | ==, !=, <, > | Member function: bool operator==(const T& other) const |
| Stream I/O | <<, >> | Friend function: friend ostream& operator<<(ostream&, const T&) |
| Subscript | [] | Member function: T& operator[](int index) |
| Assignment | = | Member function: T& operator=(const T& other) |
A few operators can't be overloaded at all: the dot operator (.), scope resolution (::), the ternary operator (?:), and sizeof. But by the end of this week, you'll be making your custom classes feel just as natural to use as the built-in types.