[   ^ to index...   |   <-- previous   |   next -->   ]

Using output streams

We print to output streams using the << operator:

int i; char b[30]; cout << i; cout << b;

The << operator is overloaded, just like >>, and hence is intelligently "aware" of the type that is being output. When given a char array, cout will treat the array as a C-style string (i.e., a null-terminated array of char). Notice therefore that the following two operations are not symmetric:

cout << myArray; cin >> myArray;

The former outputs everything in the array until the first null character, whereas the latter will read into the array until the first whitespace character.

Some more truth

We have noted that << and >> are "overloaded". In fact, these operators are overloaded in a way that is quite different from the way that addition or division are overloaded. The operator << is a "programmer-defined" overloaded operator. That is, the meaning of << with ostreams is not defined by the core language, but by the standard library.

How, you may ask, can a programmer define an overloaded operator? Well, there are a couple of different ways. Here's one:

class basic_ostream { // This line is a lie public: // ... some stuff, then: basic_ostream& operator<<(int i); basic_ostream& operator<<(char c); // and so on. };

The declarations above tell C++ that when it encounters an expression involving << with a basic_ostream object on the left, and an integer or a character on the right, it should invoke these methods on the basic_ostream with the appropriate argument.


Last modified: Wed Jun 28 20:34:27 PDT 2000