Operator Overloading  «Prev  Next»
Lesson 13Overloading I/O operators
Objective Overload input operator >> for card class.

Overloading the C++ input Operator

When overloading the operator >> to produce input to a user-defined type, the typical form is:
istream& operator>>(istream& p, user-defined type& x)

If the function needs access to private members of x, it must be made a friend of its class. A key point is to make x a reference parameter so that its value can be modified. To do this for the rational class would require placing a friend declaration for this operator in the rational class and providing its function definition.

istream& operator>>(istream& in, rational& x){
   return (in >> x.a >> x.q);

Stream Input

As you know, the >> operator is used for stream input. This operator can also be overwritten to work with new data types. For example, you can define an operator>> to read a Time object from an input stream. For simplicity, assume that the Time value is entered as three separate integers, such as

9 15 00

Here is the definition of the >> operator for Time objects:
istream& operator>>(istream&  in, Time&  a)
int hours;
int minutes;
int seconds;
in >> hours >> minutes >> seconds;
a = Time(hours, minutes, seconds);
return in;
Note that the second argument must be a non-const reference parameter, since it is modified when it is filled with the input. The >> operator should return the input stream, just like the << operator. This allows a sequence of input operations to be chained together, as they were for output, and as is illustrated in the body of the Time::operator>> function itself.

Peeking at the Input

The stream I/O library allows the programmer to peek ahead one character in the input; if you decide you don’t want the character you can put it back. For example, suppose you want to write an input function for Fraction values. You want to allow the input to be either a simple integer (such as 7) or a Fraction represented by an integer, a slash, and another integer (such as 3/4). If the next character after the numerator is not a slash, you want to push it back and return a Fraction with 1 as the denominator. You can write this function as follows:

istream& operator>>(istream& in, Fraction& r)
 int t, b;
 // Read the top
 in >> t;
 // If there is a slash, read the next number
 char c;
 in >> c;
 if (c == '/')
  in >> b;
  b = 1;
 r = Fraction(t, b);
 return in;

Overloading Stream Extraction Operator - Exercise

Click the Exercise link below to overload the input operator for the card class.
Overloading Stream Extraction Operator - Exercise