why use istream& as parameter

I see a code use istream& as parameter in a class member function.
some like this:
 
bool read(std::istream& in, int num)

why use the istream ? I think when I need the input operation, I can invoke the std::cin ,not in(the parameter), what's this for?

ps. and I saw almost every code, the writer use the declare:
#include <iostream>
#inlcude <istream> //1
#include <ostream> //2

why use last 2 explicit? the writer says write these can invoke the << and >>
but I think the <iostream> already have the <istream> and <ostream>, do we need to declare the <istream> and <ostream> explicit?
why use the istream ? I think when I need the input operation, I can invoke the std::cin ,not in(the parameter), what's this for?

What if you don't use std::cin? What if you want to use another file stream?

1
2
3
4
5
read(std::cin, n); // works

std::ifstream inputFile("file.txt");

read(inputFile, n); // also works 


I think the <iostream> already have the <istream> and <ostream>, do we need to declare the <istream> and <ostream> explicit?

It's good practice to explicitly #include whatever you use, to clarify your intent, even if another header includes it anyway.
thanks a lot
Topic archived. No new replies allowed.