Overloading Stream (<<, >>) Operators

CoderSource.net
Overloading Stream (<<, >>) Operators
Rating: 4

Date: 5/1/2004 12:00:00 AM

  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 = '\0';}
      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 value\n";
      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.

You Can Rate this Article, if you are Logged In      
 

More Links from CoderSource.net:

 
Refer to a Friend:

Your Details:

Name:     e-mail:

Friend Details:

Name:    e-mail:    


MENU
Home
MFC 
C++
.Net
WIN32
Programming
Forum
My Articles
Add to Google
Add to My Yahoo!
Welcome to Codersource.Net Login | Register | Faq  

SEARCH
Google
 

NOTES:


Thanks for visiting our CoderSource.net. This site will be improved with more articles. Interested visitors can also submit their articles through the Submit Article link.Your article will also be published after due consideration by the editor. 

© Copyright 2003. All rights on content reserved by CoderSource.net. Contact    About Us