If cout is an object of ostream class, then why can't we declare our own object, say, 'out' from the same class. i.e, isn't the following code supposed to work??
#include<iostream>
using namespace std;
int main()
{
ostream out;
out<<"something";
}
or otherwise
#include<iostream>
using namespace std;
int main()
{
ostream_withassign out;
out<<"something";
}
Stream objects require a buffer to send data to the external device. The standard output stream object, std::cout
, is initialized with a buffer the encapsulates transport to wherever your output appears. Here is a contrived example:
std::ostream cout(/* buffer */);
To make your own stream object that pretends to be the standard stream object, you can simply pass the buffer of std::cout
to its constructor. Note that I wouldn't recommend doing this in practice:
std::ostream copy(std::cout.rdbuf()); // Note: not a *real* copy
copy << "Hello World";
You didn't set the ostream object(what does this stream output to), of course you can't use it.
http://www.cplusplus.com/reference/iostream/ostream/ostream/
i.e.
// ostream constructor
#include <iostream>
#include <fstream>
using namespace std;
int main () {
filebuf fb;
fb.open ("test.txt",ios::out);
ostream os(&fb);
os << "Test sentence\n";
fb.close();
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With