Cascading of Input/Output Operators in C++
When an object calls an operator function by passing an argument and the returned value of the operator function calls the next operator function in the same expression, it is called as cascading of operators. Below are the examples for illustration of Cascading Of Operations:
In this code, Cascading of the operator is taking place here:
h4 = h1 + h2 + h3;
Here at first h1 object called (+) operator and passes h2 as an argument in the operator function call and the returned value of this operator function calls again (+) operator and passes h3 as an argument in the same expression, at last, the returned value of this second operator function is assigned in h4.
Program 2: The multiple uses of input or output operators (“>>” or ”<<”) in one statement is also an example of cascading of Input/Output operator.
- cout is an object of predefined ostream class.
- There are several insertions (“<<”) operator functions defined in ostream class for different primitive data types. For Non-primitive data types, you have to define them using the friend function.
Below is the program for overloading of ‘>>’ and ‘<<‘ operators, which takes a number N as an input continuously and insert the number N in the linked list until N = -1.
Some important points about the cascading of operators:
- There is no limit on the cascading of operators in a program.
- Operator << returns an ostream reference and has an ostream reference for the first parameter while operator >> returns an istream reference and has an istream reference for the first parameter.
- The second parameter for both the operators is always a reference to an instance of the class for which operator is overloaded.