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
obj1.display();
obj2.display();

 

But with overloading of insertion operator both the objects can be displayed conveniently as
cout<<obj1<<obj2<<endl;
Reading can also be done in similar manner.The following code illustrate the insertion and extraction operator overloading
#include<iostream>

#include<cstdlib>


using std::cin;

using std::cout;

using std::endl;

using std::istream;

using std::ostream;

using std::flush;


class Complex

{

    private:

        float real, imag;

    public:

        Complex():real(0),imag(0){}

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

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

};


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

{

    is>>C.real>>C.imag;

    return is;

}


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

{

    os<<C.real<<"+i"<<C.imag<<flush;

    return os;

}


int main()

{

    Complex C1;

    cout<<"Enter Complex Number: ";

    cin>>C1;

    cout<<"Complex Number Entered is: ";

    cout<<C1<<endl;

    system("pause");

    return 0;

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

You may also like...

Leave a Reply

Your email address will not be published.

Share