I saw the code snippet below somewhere.
#include <iostream>
int main()
{
std::ostream& os = std::cout;
os << "thanks a lot" << std::endl;
return 0;
}
Since the aforementioned code snippet works well, it indicates that std::cout is derived from std::ostream. But I can't find any direct reference yet.
As per the document, which says that[emphasis mine]:
The global objects std::cout and std::wcout control output to a stream buffer of implementation-defined type (derived from std::streambuf), associated with the standard C output stream stdout.
The above quotation says that std::cout controls ouput to a type which derived from std::streambuf other than std::cout derived from std::streambuf.
And I only find the declaration of std::cout in a file named /usr/include/c /7/iostream:
extern ostream cout; /// Linked to standard output
I can't find the implementation of std::cout.
CodePudding user response:
ostream is a class. cout is an instance of that class.
This is no different from class Person {}; Person john;. Person is the class, john is an instance of that class. The C standard library just happens to create an instance (cout) of this particular class (ostream) ahead of time, configured to write to the standard output stream.
The line std::ostream& os = std::cout; defines a new variable called os, which is of type ostream&, that is a reference to an ostream. It then makes it a reference to the already defined variable cout.
CodePudding user response:
Since the aforementioned code snippet works well, it indicates that std::cout is derived from std::ostream.
Not quite. The code works because std::cout is a std::ostream. No inheritance needed to read and understand that code example.
The above quotation says that
std::coutcontrols ouput to a type which derived fromstd::streambufother thanstd::coutderived fromstd::streambuf.
The quote is talking about details that you need not care about (unless you do care about them ;). The important part of extern ostream cout; for this quesiton is ostream cout; which means cout is an instance of type ostream (and extern just indicates that it is only a declaration while the definition (of the instance) is elsewhere, When to use extern in C ).
