C++ Operator Overloading | Unary, Binary, Stream Insertion and Extraction Operators
This complete tutorial on C++ Operator Overloading explains how to give special meaning to operators for user-defined classes. It covers unary operators, binary operators, and overloading stream insertion (<<) and extraction (>>) operators. Following best practices, this tutorial helps write intuitive and reusable object-oriented code.
Operator Overloading – Complete Tutorial
1. What is Operator Overloading?
Operator overloading allows user-defined classes to define the behavior of operators like +, -, *, <<, >>, etc.
- Makes objects behave like built-in types
- Improves code readability and reusability
2. Unary Operator Overloading
Unary operators operate on a single operand (e.g., ++, --, -).
Example: Overloading ++ (prefix)
Notes:
- Can overload prefix and postfix versions
- Use
intparameter for postfix distinction
3. Binary Operator Overloading
Binary operators operate on two operands (e.g., +, -, *, /).
Example: Overloading +
Notes:
- Can be member function or friend function
- Returns a new object for binary operations
4. Overloading Stream Insertion (<<) and Extraction (>>) Operators
Used for input/output of class objects.
Example: Stream Insertion (<<)
Example: Stream Extraction (>>)
Notes:
friendfunction required for<<and>>overloading- Improves readability and integration with streams
Best Practices
- Overload operators only when it makes logical sense
- Keep operator behavior intuitive
- Prefer member functions for unary operators
- Prefer friend functions for binary operators and streams
- Avoid overloading operators in ways that confuse users
Common Mistakes
- Returning void instead of object/reference for binary operators
- Overloading operators for unrelated operations
- Not handling const correctness
- Forgetting to pass
ostream/istreamby reference for stream operators
Summary
In this chapter, you learned C++ Operator Overloading, including:
- Unary operators (
++,--,-) - Binary operators (
+,-,*, etc.) - Stream insertion (
<<) and extraction (>>) - Best practices and common pitfalls
Operator overloading helps write clean and intuitive code that treats objects like primitive data types.