why can't we create our own ostream object

11,203

Solution 1

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";

Solution 2

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;
}
Share:
11,203

Related videos on Youtube

user1232138
Author by

user1232138

Updated on June 28, 2022

Comments

  • user1232138
    user1232138 almost 2 years

    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";
    }
    
    • David Schwartz
      David Schwartz about 12 years
      What would it do? Where would the output go?
    • jrok
      jrok about 12 years
      What is ostream_withassign supposed to be?
    • David Schwartz
      David Schwartz
      Why would it go to standard output? What in the code specifies that it should go to standard output? Standard output is a specific destination, it's not a default.
  • jrok
    jrok about 12 years
    @user1232138 You could derive from ostream and pass couts rdbuf() as ostream's constructor parameter. I'm not sure if that's a good idea, though.