Search code examples
c++stdostream

Display inputs to std::ostream


Disclaimer: I am a complete C++ beginner, and if there is a similar answer to this question, please direct me to it, as I may have missed it, not knowing much in the way of theory.

Suppose I have a method which accepts a reference to an ostream:

printAllObjects(std::ostream& os);

I am assuming it makes changes to the ostream, so that one can print the list of all of the objects to a file, say. (I might be wrong here)

Is there any way of seeing what it writes to the ostream? (via cout preferably)?


Solution

  • std::cout is an std::ostream, so just pass std::cout to the function and you'll see what it does:

    printAllObjects(std::cout);
    

    This flexibility is the very purpose of accepting a reference to std::ostream!

    Other stream types1 inheriting from the std::ostream base include:

    • std::ofstream (for file output)
    • std::ostringstream (for string output).

    1 That's not to say that std::cout is a type; it's not. It's a special, global instance of std::ostream.