Alice Chiu
Alice Chiu

Reputation: 21

Two questions about cin and cout

Creating my own cin & cout is somewhat pointless, so I just curious about how. I know that cin and cout are instances of istream/ostream class; however, I've tried some declarations like "std::istream mycin" but didn't work.

Besides, I read a lot of posts saying that cin and cout are global variables, but we have to access them through std::cin or std::cout. My understanding is that global variables are those declared in the global scope, but cin and cout are obviously in the std namespaces. Which part of my knowledge is wrong? Thanks.

Upvotes: 1

Views: 293

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

std::cin and std::cout are not just "instances of istream/ostream class". They are also connected to the C++ program's standard input and output stream.

How that happens, how that's done, is not specified by the C++ standard. Your C++ compiler and library does whatever needs to be done to make that happen, and the exact details of the underlying working is implementation defined. Merely declaring two std::istream and std::ostream objects of your own won't, of course, accomplish that by fiat. If you're interested, you can do some research and investigation, and determine how your C++ implementation or library goes about doing this, and reimplement it yourself, with your own instance of std::istream and std::ostream.

std::istream and std::ostream, by themselves, merely implement formatted input and output extraction operations using an underlying instance of a std::streambuf. std::istream and std::ostream's constructor takes a pointer to an instance of a std::streambuf that's used as the underlying input/output source/sink.

So, to summarize, in order to reimplement what std::cin and std::cout does, yourself, it is necessary to:

  1. Implement a subclass of std::streambuf that handles the underlying input and output by using your operating system-specific resources to read or write to your terminal.

  2. Use your std::streambuf subclass to construct an instance of a std::istream and/or std::ostream.

Upvotes: 6

Related Questions