r18ul
r18ul

Reputation: 1064

Why does a insertion/extraction operator's overloaded function need ostream/istream argument?

Consider the following code with overloaded insertion & extraction operators.

#include <iostream>

using namespace std;

class CTest
{
    string d_name;
public:
    friend ostream & operator<<(ostream & out, CTest & test);
    friend istream & operator>>(istream & in, CTest & test);
};

ostream & operator<<(ostream & out, CTest & test)
{
    out << "Name: " << test.d_name;
    return out;
}

istream & operator>>(istream & in, CTest & test)
{
    cout << "Enter your name: ";
    string name;
    if(in >> name)
        test.d_name = name;

    return in;
}

int main()
{
    CTest test;
    cin >> test;   // (1)
    cout << test;  // (2)
}

Following the question, what's the significance of arguments ostream & out and istream & in? Since we can see only one argument (cin >> test or cout << test), where in the caller is the ostream/istream references passed at (1) or (2)?

Upvotes: 4

Views: 1092

Answers (3)

msc
msc

Reputation: 34608

cin >> test;

Here, left operand is the cin object of type std::istream, and the right operand is your CTest class object.

Prototype of >> operator

friend istream& operator >> (istream& s, Your class &);

So, internally we have passed two arguments.

Upvotes: 0

Jan Fischer
Jan Fischer

Reputation: 71

In order to get a better understanding where the two arguments come from, you may rewrite your main() function as follows:

int main()
{
    CTest test;
    operator>>(std::cin, test);
    operator<<(std::cout, test);
}

Upvotes: 0

gsamaras
gsamaras

Reputation: 73376

Because in both cin >> test and cout << test, two arguments exist.

cin is of type istream.

cout is of type ostream.

These types could be other things than cout and cin. For example, they could be cerr, clog, or stringstream.

That's why you need two arguments, since the one is the variable for the stream and the other is the object to be streamed.

Upvotes: 4

Related Questions