Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't we create our own ostream object

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";
}
like image 992
user1232138 Avatar asked Apr 09 '12 10:04

user1232138


2 Answers

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";
like image 133
David G Avatar answered Oct 19 '22 23:10

David G


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;
}
like image 30
cloudygoose Avatar answered Oct 20 '22 00:10

cloudygoose