There are eight predefined standard stream objects that are automatically created and initialized at program startup if the header <iostream> is included. These standard stream objects are associated with the C standard files stdin, stdout, and stderr, as shown in Table 26:
Narrow character stream | Wide character stream | Associated C standard files |
cin | wcin | stdin |
cout | wcout | stdout |
cerr | wcerr | stderr |
clog | wclog | stderr |
Like the C standard files, these stream objects are all associated by default with the terminal.
The difference between clog and cerr is that clog is fully buffered, whereas output to cerr is written to the external device after each formatting. With a fully buffered stream, output to the actual external device is written only when the buffer is full. Thus clog is more efficient for redirecting output to a file, while cerr is mainly useful for terminal I/O. Writing to the external device after every formatting, to the terminal in the case of cerr, serves the purpose of synchronizing output to and input from the terminal. Also, the predefined streams are synchronized with their associated C standard files. See Section 35.6 for details.
The standard stream objects are initialized in such a way that they can be used even in constructors and destructors of non-local objects with static storage duration. However, care must be taken to always include the header <iostream> prior to the definition of any such object.
Since the initialization of the standard iostream objects is a fairly resource-intensive operation it is not advisable to include the header <iostream> just as a convenience to gain access to either or both of basic_istream and basic_ostream in translation units that do not refer to the objects. In such cases, include the headers <istream> and <ostream> instead.