walrus137's blog

By walrus137, history, 8 months ago, In English

cin >> x, just makes so much sense now.

Analogy

This thing is just syntax sugar which c++ provides.

Like when we want to write: x = x + a We can instead write: x += a

Which is exactly the same thing.

edit: these are not exactly the same things, and thus not even a good analogy, but fine to get the point.


What is operator>>

Similarly we have operator>>, which is used to take in input from an input stream. And depending on the type for the x variable two things can happen.

If x is a built-in type then cin.operator>>(x): is called, which is a member function of the cin class, and has been defined for a built-in type.

But if x is not a built-in type, then we have to manually provide how the input is going to be interpreted.

By defining a function with the below signature:

   std::istream& operator>>(std::istream& is, my_type& x){};

This is a function which takes in a reference to an input stream and a reference to our variable x and defines how x is going to be filled.

and when we do: cin >> x;

For our custom type x, the above function is called: operator>>(cin,x);

And not: cin.operator>>(x);

Since there is no member function of cin defined for type of x.

That is crazy. And just makes so much sense now, >> and << are just syntactical sugar over the actual function calls.


same for operator<<

Again for outputting two things could happen depending on the type of x.

If x is a built-int type then: ostream.operator<<(x);

If x is not a built-in type then: operator<<(ostream,x);


why cin >> x >> y >> z; works?

Now the amazing thing about why we can do this: cin >> x >> y >> z; ( symmetrically the same applies to operator<< for outputting)

This is because operator>> returns an input stream and if we remove the syntactical sugar with the actual function calls being made in order, we have something like this:

cin >> x >> y >> z;

cin.operator>>(x) >> y >> z;

cin.operator>>(x).operator>>(y) >> z;

cin.operator>>(x).operator>>(y).operator>>(z);

And this makes sense because cin.operator>>(x) returns an input stream and then we get the .operator>>() member function for that returned input stream and call that with y and so on with z.

That is just so cool and everything seems to be demystified now. That is crazy. really.

PS: This is my first blog, please point out the mistakes I made.

Full text and comments »

  • Vote: I like it
  • +46
  • Vote: I do not like it