The class std::ostream doesn't handle buffering or hardware I/O, it only handles formatting and conversions. It needs to be associated with a class derived from std::streambuf in order for that output to go anywhere:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <sstream>
int main ()
{
std::ostream stream(nullptr); // useless ostream (badbit set)
stream << "Hello World"; // nothing happens (well, failbit is also set)
stream.rdbuf(std::cout.rdbuf()); // uses cout's buffer
stream << "Hello World\n"; // prints to cout
std::stringbuf str;
stream.rdbuf(&str); // uses str
stream << "Hello World"; // writes to str
std::cout << "str = '" << str.str() << "'\n";
}
Your code above isn't the same as cout because it never calls the functions that print "Hello World" to your console.
It might help if you think about it this way (if you have read about classes, otherwise it might confuse you more ;p)
if you want to print the message "Hello World" you could think about it like this
Instead of:
1 2 3 4 5 6 7
#include <iostream>
int main ()
{
std::cout << "Hello World";
return 0;
}
To visualize what is happening it could be written like
1 2 3 4 5 6 7
#include <iostream>
int main ()
{
std::cout.operator<<("Hello World");
return 0;
}
Then the "Hello World" would get passed to the operator and it would do it's magic to print it on your screen. (I could be wrong but this is how I'm imagining that it works)
Bascially cout is an ostream that calls the function to print the stream to your console.