Main Content

Left shift operator on an output stream object - C++

Archive - Originally posted on "The Horse's Mouth" - 2015-10-30 09:49:09 - Graham Ellis

When explaining "Hello World" in C++ (see here), delegates who are already familiar with programming in other languages pick up on the line
  cout << "Welcome - and enjoy your C++ course" << endl;
and ask for an explanation.

Yes - it is a bit different, isn't it?

The explanation and a full understanding come during the course though, and not necessarily at the early stage. But here goes:

The << operator is described (in C++ documentation) as the left shift operator, and indeed when used on an int data type, it takes the bit pattern that defines the integer and shifts it to the left by the number of bits given - for example:
  int value = 13;
  value = value << 2;

would take the internal format of the integer 13 (1101) and shift it 2 left (110100) - or 52 in decimal.

cout is an output stream object - and the concept of doing a "left shift" on a stream is a nonsense idea, so the authors of C++ used the operator which was going "spare" for something else - to send the contents of the expression to the right of the << to the stream named on its left.

The << operation on an output stream returns a reference to the stream, thus allowing further << operations to be concatanated onto the first one - allowing for a series out outputs in a single expression.

Full example of shifting in C++ [here] ... note that for an input stream (our example uses cin, the >> operator (right shift) is also overloaded, indicating that data from the input stream is sent to the named variable.