Overloading stream insertion and extraction(<<,>>) operators in C++


In C++, stream insertion operator “<<” is used for output and extraction operator “>>” is used for input.
We must know following things before we start overloading these operators.
1) cout is an object of ostream class and cin is an object istream class
2) These operators must be overloaded as a global function. And if we want to allow them to access private data members of class, we must make them friend.
Why these operators must be overloaded as global?
In operator overloading, if an operator is overloaded as member, then it must be a member of the object on left side of the operator. For example, consider the statement “ob1 + ob2” (let ob1 and ob2 be objects of two different classes). To make this statement compile, we must overload ‘+’ in class of ‘ob1’ or make ‘+’ a global function.
The operators ‘<<' and '>>' are called like 'cout << ob1' and 'cin >> ob1'. So if we want to make them a member method, then they must be made members of ostream and istream classes, which is not a good option most of the time. Therefore, these operators are overloaded as global functions with two parameters, cout and object of user defined class.

PROGRAM:
//By Vikas
#include<iostream>
using namespace std;
class Student
{
    int rno;
    public:
    friend void operator >> (istream &in,Student &ob1);
    friend void operator << (ostream &out,Student &ob2);
};
void operator >> (istream &in,Student &ob1)
{
    cout<<"\nEnter Roll no:";
    in>>ob1.rno;
}
void operator << (ostream &out,Student &ob2)
{
    out<<"\nYou had entered:\n";
    out<<ob2.rno;
}
int main()
{
    Student s;
    cin>>s;
    cout<<s;
    return 0;
}

Recommended: solve it on “PRACTICE ” first, before moving on to the solution.




Previous Post Next Post