How does the stream manipulators work?

Posted by Narek on Stack Overflow See other posts from Stack Overflow or by Narek
Published on 2011-01-08T12:32:59Z Indexed on 2011/01/08 12:54 UTC
Read the original article Hit count: 150

Filed under:
|
|
|

It is well known that the user can define stream manipulators like this:

ostream& tab(ostream & output)
{
    return output<< '\t';
} 

And this can be used in main() like this:

cout<<'a'<<tab<<'b'<<'c'<<endl;

Please explain me how does this all work? If operator<< assumes as a second parameter a pointer to the function that takes and returns ostream &, then please explain my why it is necessary? What would be wrong if the function does not take and return ostream & but it was void instead of ostream &?

Also it is interesting why “dec”, “hex” manipulators take effect until I don’t change between them, but user defined manipulators should be always used in order to take effect for each streaming?

© Stack Overflow or respective owner

Related posts about c++

Related posts about iostream