Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass in fstream where ifstream expected

Tags:

c++

casting

void foo(ifstream &ifs)
{
    //do something
}

int main()
{
    fstream fs("a.txt", fstream::in);
    foo(fs); //error, can't compile
}

The above code can't compile, seems like I can't initialize an ifstream & with a fstream object? What if I do it this way:

foo(static_cast<ifstream>(fs)); 

or

foo(dynamic_cast<ifstream>(fs)); 
like image 899
Alcott Avatar asked Apr 01 '12 01:04

Alcott


1 Answers

Probably you want foo() to take istream. As indicated in the comments, this is a base type for both ifstream and fstream.

void foo( istream & is )

There is a nice reference for these classes at cplusplus.com:

  • http://www.cplusplus.com/reference/iostream/istream "Input stream"
  • http://www.cplusplus.com/reference/iostream/ifstream "Input file stream class"
  • http://www.cplusplus.com/reference/iostream/fstream "Input/output file stream class"
like image 171
Brent Bradburn Avatar answered Sep 27 '22 17:09

Brent Bradburn