Milad Khajavi
Milad Khajavi

Reputation: 2859

How C++ determine arguments of overloaded operators?

I have overloaded I/O operators:

struct Time {
  int hours;
  int minutes;
};

ostream &operator << ( ostream &os, Time &t ) {
  os << setfill('0') << setw( 2 ) << t.hours;
  os << ":";
  os << setfill('0') << setw( 2 ) << t.minutes;
  return os;
}

istream &operator >> ( istream &is, Time &t ) { 
  is >> t.hours;
  is.ignore(1, ':');
  is >> t.minutes;
  return is;
}

I want to know when I call cin >> time how compiler determine is &is argument. here is my main() program:

operator>>( cin, time );
cout << time << endl;

cin >> (cin , time);
cout << time << endl;

cin >> time;                     //Where is cin argument???
cout << time << endl;

Upvotes: 1

Views: 100

Answers (1)

Joseph Mansfield
Joseph Mansfield

Reputation: 110668

cin >> time;

This is operator >> with two operands. If the overloaded operator function is found as a non-member, then the left operand becomes the first argument and the right operand becomes the second argument. So it becomes:

operator>>(cin, time);

So the cin argument is just the first operand to the operator.

See §13.5.2 of the standard:

A binary operator shall be implemented either by a non-static member function (9.3) with one parameter or by a non-member function with two parameters. Thus, for any binary operator @, x@y can be interpreted as either x.operator@(y) or operator@(x,y).

If you're wondering how this applies to chained operators, take this:

cin >> time >> something;

This is equivalent to:

(cin >> time) >> something;

Which is also equivalent to:

operator>>(operator>>(cin, time), something);

Upvotes: 4

Related Questions