Bharat Arya
Bharat Arya

Reputation: 139

Overloading input/output operators in C++

#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;
}

What is the use of passing the operator as a reference "& operator". When we pass a normal operator we never pass the reference, but in the above code, we are passing the reference to the operator. Can anyone explain the part where operator reference is passed?

Upvotes: 1

Views: 840

Answers (2)

Robert Andrzejuk
Robert Andrzejuk

Reputation: 5232

Generally if a Declare one name (only) per declaration rule is adhered to, then this allows to consistantly write a pointer/refrence "stuck" next to the type as:

istream& operator>> (istream& in,  Complex& c)
{ //...

In this way it can be seen that the function named operator>> is returning a type istream& (a reference to an istream object).

This function takes 2 variables:

  • in of the type istream& (a reference to an istream object),
  • c of the type Complex& (a reference to a Complex object).

and similarly for:

ostream& operator<< (ostream& out, const Complex& c)
{ //...

The formatting of the code does not in anyway affect how the code is compiled. So the functions definitions in this answer are exactly the same as in the question.


As to why use a reference, I suggest to read: When to use references vs. pointers

Upvotes: 0

Igor P.
Igor P.

Reputation: 76

In the code friend ostream & operator << the & is associated with the type overloaded operator returns. So that it returns ostream & and istream & for the second one.

The overloaded operators:

  1. Take the reference to istream or ostream object whcih is I/O object like cin/cout for console I/O or other type of stream object (I/O from/to string, etc).
  2. Affect the state of the object so that data is read/written.
  3. Return the reference to that object so that you can use these operators in sequence like:

    Complex c1
    Complex c2;
    cin >> c1 >> c2;
    

Upvotes: 5

Related Questions