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.

  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.

Close    To Top
  • Prev Article-Programming:
  • Next Article-Programming:
  • Now: Tutorial for Web and Software Design > Programming > cplus > Programming Content
    Photoshop Tutorial
     

    Special Effect

      3D Effect
      Photoshop Articles
    Programming Tutorial
     

    C/C++ Tutorial

      Visual Basic
      C# Tutorial
    Database Tutorial
     

    MySQL Tutorial

      MS SQL Tutorial
      Oracle Tutorial
    Geek Tutorial
     

    Blogging Tutorial

      RSS Tutorial
      Podcasting Tutorial
    Graphic Design Tutorial
      Coreldraw Tutorial
      Illustrator Tutorial
      3D Tutorials
    Webmaster Articles
     

    Domain Service

      Web Hosting
      Site Promotion
    Java Tutorial/ Articles
     

    Java Servlets

      JavaEE Tutorial
     

    JavaBeans Tutorial

    XML Tutorial/ Articles
     

    XML Style

      AJAX Tutorial
      XML Mobile
    Flash Tutorial/ Articles
     

    Flash Video

      Action Script
      Flash Articles
    OS Tutorial/ Articles
      Linux Tutorial
      Symbian Tutorial
      MacOS Tutorial
    Personal Tech
      Hardware Tutorial
      Software Tutorial
      Online Auction