Overloading input/output operators in C++

In C++, stream insertion operator << is used for output and stream extraction operator >> is used for input.

cout is an object of ostream class which is a compiler defined class. When we do cout<<obj where obj is an object of our class, the compiler first looks for an operator function in ostream, then it looks for a global function. One way to overload insertion operator is to modify ostream class which may not be a good idea. So we make a global method and if we want to allow them to access private data members of class, we must make them friend.

#include <iostream>using namespace std; class Complex{private: int real, imag;public: Complex(int r = 0, int i =0) { real = r; imag = i; } friend ostream & operator << (ostream &out, const Complex &c); friend istream & operator >> (istream &in, Complex &c);}; ostream & operator << (ostream &out, const Complex &c){ out << c.real; out << “+i” << c.imag << endl; return out;} istream & operator >> (istream &in, Complex &c){ cout << “Enter Real Part “; in >> c.real; cout << “Enter Imagenory Part “; in >> c.imag; return in;} int main(){ Complex c1; cin >> c1; cout << “The complex object is “; cout << c1; return 0;}


No Responses

Write a response