Operator Overloading¶
Operator overloading allows you to define custom behaviors for C++ standard operators (such as +, -, *, <<, []) when applied to your user-defined classes. This allows your classes to act with the same intuitive syntax as built-in types (like int or float).
1. Member vs. Non-Member Overloads¶
When overloading an operator, you must choose between defining it as a member function of the class or as a non-member function (often declared as a friend to access private members).
1. Member Operator Overload¶
A member operator uses the implicit this pointer as the left-hand operand.
2. Non-Member (Friend) Operator Overload¶
If the left-hand operand of an operator is a different type (like a float or an output stream), the operator cannot be a member function. It must be written as a non-member function.
For example, supporting scalar multiplication on both sides:
2. Stream Insertion (<<) and Extraction (>>)¶
Interfacing with streams like std::cout or std::cin requires overloading the shift operators << and >>. These must be non-member functions because std::ostream / std::istream are on the left-hand side.
They must return a reference to the stream object (std::ostream&) to support method chaining (e.g. std::cout << a << b;).
3. Increment and Decrement Overloads¶
To distinguish between the prefix (++x) and postfix (x++) forms, C++ uses a dummy int parameter in the signature for the postfix form.
temp object is why prefix ++i is preferred for loops where the old value is not needed.
4. The Copy-and-Swap Idiom¶
When overloading the copy assignment operator (operator=), you must ensure exception safety and guard against self-assignment (e.g. x = x).
The Copy-and-Swap Idiom is the cleanest, most robust pattern to handle assignment safely.
- Leverage the copy constructor to create a temporary copy (handles allocation and exception checks first).
- Swap the contents of the temporary copy with the current object.
- Let the temporary object go out of scope, destroying the old resources automatically.
5. Non-Overloadable Operators¶
C++ forbids overloading a handful of operators to maintain syntax integrity:
- . (Member access)
- .* (Member pointer dereference)
- :: (Scope resolution)
- ?: (Conditional / Ternary)
- sizeof (Object size)
Related Guides¶
- Classes and Objects — Constructors, destructors, and Rule of Five details.
- Operators — Built-in operator precedence rules.