Alcott
Alcott

Reputation: 18585

pass in fstream where ifstream expected

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)); 

Upvotes: 5

Views: 3166

Answers (1)

Brent Bradburn
Brent Bradburn

Reputation: 54939

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:

Upvotes: 6

Related Questions