Overloading Stream (<<, >>) Operators


Operator overloading is a beautiful concept in C++. At times it is little confusing also. But actually they are quite easy. Anyway, here is an example for overloading the stream operators.

The best way to overload the stream operators is not to make them members of any class, but to keep them as friends. i.e., wherever there is a need to use the stream operators, use them as friend functions with the suitable parameters.

Operator overloading is a beautiful concept in C++. At times it is little confusing also. But actually they are quite easy. Anyway, here is an example for overloading the stream operators.

The best way to overload the stream operators is not to make them members of any class, but to keep them as friends. i.e., wherever there is a need to use the stream operators, use them as friend functions with the suitable parameters.
The following example shows the use of these operators for a class.


#include <iostream.h>
#include <string.h>
class Base
{
char strVal[100];
public:
Base(){ strcpy(strVal,”");}
Base(char *val){ strcpy(strVal,val);}
~Base(){*strVal = ”;}
friend istream& operator >>(istream &is,Base &obj);
friend ostream& operator <<(ostream &os,const Base &obj);
};
istream& operator >>(istream &is,Base &obj)
{
is>>strVal;
return is;
}
ostream& operator <<(ostream &os,const Base &obj)
{
os<<obj.strVal;
return os;
}
void main()
{
Base b;
cin>>b;
cout<<”Printing the valuen”;
cout<<b<<endl;
}


If there are derived classes which need to use the stream operators, one way is to define some more versions of the stream operators with the derived class Parameters.