Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the output operator 'os << value' and not 'value >> os'?

Tags:

c++

I am learning about streaming. The standard streams provide the << operator which can be declared as:

ostream& operator<<(stream& os, CLASS& rc);  

Why is it impossible to declare it as this?

ostream& operator>>(CLASS& rc, stream& os); 

Then I may be able to do something like:

rc.something >> os;

as part of its implementation.


Edit as people have helped me learn more about this, I am thankful.

However I am stuck at how to implement actually it.

I have tried

ostream& operator >> (const SomeClass& refToCls, stream& os)
{
   refToCls.iVar >> os;
   return os;
}

but it fails. How can I fix it?

like image 616
Dalton Avatar asked Dec 31 '25 11:12

Dalton


1 Answers

In fact it's possible to define

ostream& operator>>(CLASS& rc, ostream& os);

But then you must chain it like this:

a >> (b >> (c >> str));

The >> operator is left-associative, so by default this:

a >> b >> c >> str;

is equivalent to:

((a >> b) >> c) >> str;

which has a wrong meaning.

like image 126
Yakov Galka Avatar answered Jan 02 '26 01:01

Yakov Galka