moonman239 moonman239 - 1 year ago 61
C++ Question

Exactly how do << and >>, as used in streams, work?

I always thought of cout and cin calls as something like this:

cout << someVar

tells the compiler we're dumping the value of someVar into cout, just as we could dump water into a physical stream. Likewise,

cin >> someVar

tells the compiler to fill someVar with data from cin (everything before whitespace), just as we might fill a bucket with water from a physical stream.

But << and >> are bitwise operators. << shifts the bits to the left, while >> shifts the bits to the right. Why doesn't, say,
cout << Hello World
cout << My name is John
make the console not say "Hello World"?

Edit: This is not a duplicate of "Operator overloading" because while that question may implicitly address the << and >> operators, my question as presently constituted does not address overloading.

Answer Source

In C++ you can overload operators. Here >> and << are such overloaded operators, in this case members of std::basic_ostream (std::basic_istream), of the form

std::basic_ostream& operator<<(int); // overload for int

So when you write

std::cout << 42;

the call is translated to


Note that operator<< and operator>> can also be defined as non-member functions, in which case they have a form similar to:

std::basic_ostream& operator<<(std::basic_ostream& os, const Foo& foo)

where Foo is some custom type. This is how you implement in general stream extraction and insertion, overloading the non-member operator<< or operator>>, since you don't have access to the internals of std::basic_ostream or std::basic_istream.

See e.g. this for more details.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download