Operator Overloading¶
Operator overloading allows you to define how standard operators (like +, -, <<) work with your custom classes. This makes your types behave like built-in types.
Basic Syntax¶
You define a function with the name operator@, where @ is the symbol.
Friend Functions for Overloading¶
Sometimes you need to overload an operator where the left-hand side is not your class (e.g., std::cout << obj).
Common Operators to Overload¶
- Arithmetic:
+,-,*,/ - Comparison:
==,!=,<,>(Or<=>in C++20) - Stream Insertion:
<<(for printing) - Subscript:
[](for array-like access) - Function Call:
()(Functors)
The Spaceship Operator (<=>) (C++20)¶
In C++20, you can default the three-way comparison operator to automatically generate all comparison operators.