Stream Insertion and Extraction Operator Overloading
In C++, stream insertion operator “<<” is used for output and extraction operator “>>” is used for input.
As we all know cout is an object of ostream class and cin is an object of istream class. Insertion and extraction operators functions must be overloaded as global functions. And if we want to allow them to access private data members of class, we must make them friend.
Why to Overload << and >>
If we do not overload insertion and extraction operators and we insert or extract any object as below given example
#include<iostream.h>
class Hey
{
private:
int x;
};
void main()
{
Hey h;
// It will generate compilation error
cin>>h;
cout<<h;
getch();
} |
Clearly this will generate compilation error as an object of any class can not be inserted or extracted. To overcome this issue we overload these operators.
Insertion and extraction operators can not be a member of any class as cin and cout are not objects of that class. So these functions must be global functions and to access private members of the class these must be declared friend.
Example
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class Check
{
private:
float x,y;
//Declaring insertion and extraction operators as friend of class Check
friend istream& operator >>(istream&,Check&);
friend ostream& operator <<(ostream& output,Check& obj);
};
//Defining insertion and extraction operators
istream& operator >>(istream& input,Check& obj)
{
input>>obj.x>>obj.y;
return input;
}
ostream& operator <<(ostream& output,Check& obj)
{
output<<"\nx:"<<obj.x<<" y:"<<obj.y;
return output;
}
void main()
{
clrscr();
Check c;
cin>>c;
cout<<c;
getch();
} |
Output
For more Object Oriented Programming Lab Experiments Click Here