Operator Overloading in C++
Operator overloading gives class types natural syntax: + concatenates, == compares, << streams, [] indexes. Implemented as specially-named functions (operator+, operator==), they should mirror built-in meaning — + that deletes files is a betrayal, not cleverness.
Symmetric operators (a + b where either side may convert) belong outside the class as free functions, often friends; assignment-like ones (+=, =, []) belong inside. Some operators can't be overloaded (., ::, ?:, sizeof), and precedence/arity never change — overloading borrows spelling, not grammar.
Mirror built-in meaning
+ should combine, == should test equivalence, << should stream — surprising semantics make code unreadable.
Members vs free functions
Compound assignment and subscript need the left object (members); symmetric + and << need conversions on both sides (free functions).
Implement + via +=
Write the mutating operator+= as a member, then a free operator+ that copies and applies it — one logic, two spellings, consistent behavior.
Know the limits
., ::, ?:, sizeof, and .* resist overloading; precedence and arity are fixed — you extend vocabulary, never syntax.
#include <iostream> class Counter {public: int n = 0; Counter& operator+=(int k) { n += k; return *this; } bool operator==(const Counter& o) const { return n == o.n; }}; int main() { Counter c; c += 5; Counter d; d += 5; std::cout << c.n << ", " << (c == d) << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.