Overloading the Stream Extraction Operator (>>>)


Rather than writing a custon read method for a class, it can be convenient to overload the stream extraction operator to work with our new data type.

Because the left operand of the stream extraction operator is an object of class istream (like cin and not an object of our new class, we must overload the operator as a standalone function.

Here is the skeleton code for overloading the stream extraction operator:

istream& operator>>(istream& is, ClassName& obj)
{
    // Read values into the data members of obj using it like you would using cin
   
    // Return the input stream object so the operator may be cascaded correctly

    return is;
}

Example 1: The >> operator overloaded as a standalone friend function of the Rational class

To designate our overloaded operator function as a friend of the Rational class, we need to include the function's prototype, preceded by the keyword friend, anywhere in the declaration of the Rational class:

class Rational
{
    friend istream& operator>>(istream&, Rational&);

private:
    int numerator,
        denominator;

public:
    .
    .
    .
};

The function definition can then be coded like so:

istream& operator>>(istream& is, Rational& obj)
{
    char unused;
  
    is >> obj.numerator;      // Read numerator
    is >> unused;             // Read / and ignore it
    is >> obj.denominator;    // Read denominator

    // Return the input stream object so the operator may be cascaded correctly

    return is;
} 

Once weve overloaded this operator, we can use it to read data into an object of the Rational class from the keyboard using cin:

Rational r1;     // Create a new empty Rational object using the default constructor

cout << "Please enter a rational number as numerator/denominator: "

cin >> r1;       // Generates the function call operator>>(cin, r1)  

This is not something that you're likely to want to do for every class you create - it wouldn't be very practical for a class with many data members, for example. You can also run into issues with array overflow when reading C strings.

Cascading the Stream Extraction Operator

Like the stream insertion operator, the stream extraction operator can be cascaded to read more than one item in a single statement, e.g.:

Rational r1, r2;

cout << "Please enter two rational numbers as numerator/denominator, separated by whitespace: "
cin >> r1 >> r2;

The return value from the overloaded operator function is required in order to cascade the operator correctly.

Using an Overloaded Stream Extraction Operator for File Input

Writing an overloaded operator function to use the >> operator to read from a file stream is trivial - simply replace the data type istream with the data type ifstream in the function prototype and definition. Of course, you'll have to open the file stream object for input before you can read from it.