Learn C++
#include "oopadvanced/operator_overloading.hpp"

Operator Overloading in C++

//concept

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.

//how it works
1

Mirror built-in meaning

+ should combine, == should test equivalence, << should stream — surprising semantics make code unreadable.

2

Members vs free functions

Compound assignment and subscript need the left object (members); symmetric + and << need conversions on both sides (free functions).

3

Implement + via +=

Write the mutating operator+= as a member, then a free operator+ that copies and applies it — one logic, two spellings, consistent behavior.

4

Know the limits

., ::, ?:, sizeof, and .* resist overloading; precedence and arity are fixed — you extend vocabulary, never syntax.

//example
#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;
}
Output
5, 1
1c += 5 invokes the member operator+=, adding in place and returning *this for chaining.
2c == d calls the const member operator==, comparing stored values — true (1) since both hold 5.
3Both print as computed: class instances manipulated with built-in-looking syntax.
//use cases
Numeric types (complex, matrices, big integers) with arithmetic syntax
Streamable, comparable value objects across a codebase
Containers with operator[] indexing that reads like arrays
Chained += and << built on single well-tested primitives

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.