I’m trying to understand what’s really happening when I compile and execute C++ code, but the line cout << "output"; has me a bit confused.
I know that the <<, operator is the bitwise leftshift operator, and that executing y = x << 6 will assign the value to y that resulted from shifting x to the left by six bits.
I also know that ‘<<‘, with respect to streams, is the insertion operator, and that executing cout << "output"; inserts the string output into the object cout.
What I want to know is whether this is an example of the overloading of <<, or if cout really is being shifted to the left by a value that corresponds to the number of bits occupied by the string output. If the output really is just being inserted into cout via the overloading of <<, then why has the bitwise operator been used rather than the assignment operator =, which would be rather more intuitive?
Question: How does cout << "output" place the word “output” on my terminal screen?
In a word, the << operator is overloaded (a very common c++ feature).
Just like other methods, operators may be overloaded, and as hinted by Martin York in his response, operators are little more than methods which the compiler invokes when it parses an operand and operator expression.
What happens is that when applied to operands of type integer and such << has the “typical”, bitwise operator semantics, when applied to a stream it has “printf-like” semantics.
cout is a object of type ostream. See details for its ostream::operator<<
Effectively the ostream::operator<< is overaloaded multiple times, for each of the possible types of the its second argument (on its right side). This allows feeding a stream with various types and not having to specify a format. This operator returns an ostream which allows chaining several << together.
The reason why << was chosen for the ostream operator is that is allows showing in the line code things in the same order as they will appear in the output:
this is thought to be easier to read, and is also less error prone than say