8

I'm taking a quiz on an intro level class in C++ and I'm trying to understand a question. After searching the internet and not getting an answer, so here I am.

Which of the following function declarations will accept either cout or a file stream 
object as its argument?

A. void output( fstream &outFile);  
B. void output( ofstream &outFile); 
C. void output( ostream &outFile);  
D. void output( iostream &outFile);

The answer is C.

I know the difference between: fstream, ofstream, ostream, iostream.

What I don't understand is why none of the other options are able to accept the cout or file stream object as an argument.

Is the answer as simple as ostream objects contain data (char,etc) that are able to be passed as arguments?

Any information would be greatly appreciated.

  • 7
    Perhaps [this C++ I/O reference](http://en.cppreference.com/w/cpp/io) and its inheritance hierarchy diagram can help? – Some programmer dude Oct 11 '17 at 14:04
  • Related: [Is it possible to pass derived classes by reference to a function taking base class as a parameter](https://stackoverflow.com/questions/9285627/is-it-possible-to-pass-derived-classes-by-reference-to-a-function-taking-base-cl) – Borgleader Oct 11 '17 at 14:07
  • 1
    I would choose `D` because a file stream can be input and output. Answer `C` is output only. – Thomas Matthews Oct 11 '17 at 14:09
  • 2
    @ThomasMatthews: `D` doesn't work because you can't pass `std::cout` to it; it's not an `std::istream`. – Cornstalks Oct 11 '17 at 14:09
  • If I have an `ifstream` for reading, which is a file stream, I can't use `C`. The question should be reworded. :-) – Thomas Matthews Oct 11 '17 at 14:12
  • @ThomasMatthews The function is called *output*. How confusing would that be if it read from a file? – Borgleader Oct 11 '17 at 14:14

1 Answers1

6

The answer is C. The question is about the inheritance hierarchy. std::cout is an instance of std::ostream. All other functions accept subclasses of std::ostream and can therefore not handle std::cout. std::fstream could be passed to all of them but the question was about both.

Samer Tufail
  • 1,835
  • 15
  • 25
MichaelE1000
  • 289
  • 2
  • 14