Friday, November 25, 2011

Stream Operator (Insertion(<<) and Extraction (>>)) Overloading in C++

The stream can be used not only with standard data types nut also with user defined classes. The C++ lets us treat user-defined data types in the same way as that of built in types like int or cahr. To read and display user defined data types like the built in data type, we have to overload the stream extraction (>>) and insertion (<<) operators to accept the user defined data. We can overload the stream the stream operator to read keyboard input and display output for user defined classes. After overloading the stream operator, single input/output statement can be used for input/output of user defined data reducing the number of statements. Without stream operator overloading,    we need to define member function like display() for a class and call them as

But with overloading of insertion operator both the objects can be displayed conveniently as
Reading can also be done in similar manner.The following code illustrate the insertion and extraction operator overloading.

using std::cin;
using std::cout;
using std::endl;
using std::istream;
using std::ostream;
using std::flush;

class Complex
        float real, imag;
        friend istream & operator>>(istream &is, Complex &C);
        friend ostream & operator<<(ostream &os, Complex &C);

istream &operator >> (istream &is, Complex &C)
    return is;

ostream &operator << (ostream &os, Complex &C)
    return os;

int main()
    Complex C1;
    cout<<"Enter Complex Number: ";
    cout<<"Complex Number Entered is: ";
    return 0;

No comments:

Post a Comment