![]() |
VOOZH | about |
Stream operator overloading lets us redefine the input (>>) and output (<<) operators for user-defined classes. This lets custom objects interact with cin and cout like built-in types, making input/output intuitive and readable.
Enter real and imaginary parts: The complex number is: 0 + i0
Explanation: This program overloads the >> and << operators to allow easy input and output of Complex objects. It uses friend functions to access private members and format input/output like built-in types.
When overloading stream operators, the following rules must be followed:
In operator overloading, if an operator is overloaded as a member, then it must be a member of the object on the left side of the operator. For example, consider the statement "ob1 + ob2" (let ob1 and ob2 be objects of two different classes). To make this statement compile, we must overload '+' in a class of 'ob1' or make '+' a global function.
The operators '<<' and '>>' are called like 'cout << ob1' and 'cin >> ob1'. So if we want to make them a member method, then they must be made members of ostream and istream classes, which is not a good option most of the time. Therefore, these operators are overloaded as global functions with two parameters, cout and object of user-defined class.