Overloading Stream Operators
The predefined objects cin and cout are used to perform various input/output operations in C++. The extraction operator (>>) is used with cin object to carry out input operations. The insertion operator (<<) is used with cout object to carry out output operations. In Chapter 2 we learnt how to create objects similar to cin and cout. It is also possible to overload both these extraction and insertion operators with friend function.
The syntax for overloading (<<) insertion operator is as follows:
The keyword friend precedes the declaration. The ostream is an output stream class followed by reference and keyword operator. The put is an output stream object like cout. The v1 is a user-defined class object. The following program explains overloading of insertion operator with friend function.
10.19 Write a program to overload insertion operator (<<) with friend function.
Explanation: In the above program the insertion operator << is overloaded with friend function. The overloaded operator allows us to display contents of object directly using cout statement. The statement cout<<s; displays contents of object s on the screen.
Similarly, extraction operator can be overloaded. The syntax for overloading extraction operator is as follows:
The following program explains overloading of extraction operator.
10.20 Write a program to overload extraction operator using friend function.
Explanation: This program is same as the previous one. Here, extraction operator is overloaded. The object s is directly used with cin statement. After execution of this statement, the overloaded operator is invoked.