Operator Overloading
Teach the built-in operators how to work with your own types
+, == or << is really just a function with a symbolic name. When you write a class, you can supply your own version of that function so a + b, a == b or cout << a behave sensibly for your type — exactly as they do for int and string.
- overload arithmetic and comparison operators (
+,==,<) for your own class, - choose correctly between a member operator and a free (non-member) operator,
- overload
operator<<for streams and usefriendwhen private data is needed, - apply
const-correctness and the right return types (value vs. reference), - recognise what you cannot do, and use the C++20
<=>shortcut.
1. An operator is a function in disguise
Think of the compiler as a translator. When it sees a + b, it does not have a hard-wired notion of "plus" for your class. Instead it looks for a function literally named operator+ that accepts operands of those types. If it finds one, it calls it; if it does not, the code fails to compile.
Analogy. The + symbol is like the word "combine". For numbers, "combine" means add. For strings it means join. For a shopping cart it might mean "merge two carts". The symbol stays the same, but you decide what combining means for your type — just as a single verb takes on different jobs in different contexts.
This is what makes user-defined types feel like first-class citizens. A Money, a Vector2D or a Matrix can be added, compared and printed with the same clean syntax as an int, instead of forcing readers to call a.add(b) everywhere.
a + b into a member call or a free-function call, depending on how you declared the operator.