- We know that insertion (<<) and extraction (>>) are operators in C++ and just like other operators we can also overload this insertion and extraction operators. In this post I will show you how to overload insertion and extraction operators just like other operators.
- Consider the example of class ‘Box’ in which we want to read and print the data members of class by overloading insertion and extraction operator.
// Program to overload insertion and extraction operator
#include "iostream.h"
#include "conio.h"
class Box
{
double height;
double width;
double vol ;
public :
friend istream & operator >> (istream &, Box &);
friend ostream & operator << (ostream &, Box &);
};
istream & operator >> (istream &din, Box &b)
{
clrscr();
cout << "Enter Box Height: " ; din >> b.height ;
cout << "Enter Box Width : " ; din >> b.width ;
return (din) ;
}
ostream & operator << (ostream &dout, Box &b)
{
dout << endl << endl;
dout << "Box Height : " << b.height << endl ;
dout << "Box Width : " << b.width << endl ;
b.vol = b.height * b.width ;
dout << "The Volume of Box : " << b.vol << endl;
getch() ;
return(dout) ;
}
void main()
{
Box b1;
cin >> b1;
cout << b1;
}
- In above example we are overloading insertion and extraction operator using friend function.
- For insertion operator overloading we are passing two arguments.
- One is object (‘dout’) of class ‘ostream’ and another is object (‘b’) of class “Box”. Also that function returns the object of type ‘ostream’ as ‘dout’.
- You can use any name you like instead of dout.