Module 17: Operator OverloadingIntermediate45 min read
Operator Overloading Rules, Arithmetic & Stream (<< / >>) Operators
Learn which operators can be overloaded, member vs friend non-member overloads, overloading +, ==, ++, and << / >> stream operators.
Key Takeaways & Core Concepts
- Cannot Overload:
::,.,.*,?:,sizeof,typeid. - Member vs. Friend Non-Member: Binary operators like
+or==are often non-members for symmetry;<<and>>must be non-memberfriendfunctions because the left operand isstd::ostream&/std::istream&.
1. Rules & Non-Overloadable Operators
Operator overloading gives user-defined types intuitive syntax (c1 + c2, cout << c).
- Cannot Overload:
::,.,.*,?:,sizeof,typeid. - Member vs. Friend Non-Member: Binary operators like
+or==are often non-members for symmetry;<<and>>must be non-memberfriendfunctions because the left operand isstd::ostream&/std::istream&.
1. Overloading +, ==, Pre/Post ++ and <<
1#include <iostream>
2
3class Counter {
4 int val;
5public:
6 explicit Counter(int v = 0) : val(v) {}
7 Counter& operator++() { ++val; return *this; }
8 Counter operator++(int) { Counter old = *this; ++val; return old; }
9 bool operator==(const Counter& o) const { return val == o.val; }
10 friend std::ostream& operator<<(std::ostream& os, const Counter& c) { return os << c.val; }
11};
12
13int main() {
14 Counter c(5);
15 std::cout << "Post: " << c++ << ", Now: " << c << ", Pre: " << ++c << "\n";
16 return 0;
17}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
17 lines
Note: Implements both pre- and post-increment with standard C++ semantics.
2. Pre-Increment vs. Post-Increment
- Pre-increment
T& operator++()mutates and returns*this. - Post-increment
T operator++(int)takes a dummyintparameter, saves old state, increments, and returns the old copy.
Practice & AssessmentC++ Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)