std::cout constructor

For a little while, I've sort of been trying to come up with a way to form an std::iostream object that inputs and outputs to the console. To do so, I'm trying to figure out what sort of constructor std::cout uses to construct itself. Obviously, the only public one is the one that accepts a streambuf*, but being an abstract base class, I'd need to form a filebuf* or a stringbuf*, and it doesn't seem to me that either can direct to the command line very easily for some reason. Is there any way to do what I've been trying to accomplish?
Couldn't you just do something like this:

1
2
3
4
5
6
7
class Console {
    std::ostream& out;
    std::istream& in;
public:
    Console() : out(std::cout), in(std::cin) {}
    //overload operators here...
};
That works. (I do feel like making it an actual std::iostream object, but oh well. Too lazy to overload all the operators, so I might use multiple inheritance.)

EDIT: This doesn't seem to be doing anything.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

class Cons : public std::ostream,public std::istream
{
public:
    Cons() : std::ostream(std::cout.rdbuf()),std::istream(std::cin.rdbuf()){}
    Cons(std::streambuf* buf) : std::ostream(buf),std::istream(buf){};
};

namespace std
{
    Cons cio;
}

int main()
{
    std::cio << "What's your name?" << std::endl;
    std::string name;
    std::getline(std::cio,name);
    std::cio << "Hello, " << name << "!" << std::endl;
}
Last edited on
Topic archived. No new replies allowed.