How would one go about casting a ifstream into a istream. I figure since ifstream is a child of istream I should be able to do so but I have been having problems with such a
Try:
std::ifstream* myStream;
std::istream* myOtherStream = static_cast<std::istream*>(myStream);
myOtherStream = myStream; // implicit cast since types are related.
The same works if you have a reference (&) to the stream type as well. static_cast
is preferred in this case as the cast is done at compile-time, allowing the compiler to report an error if the cast is not possible (i.e. istream
were not a base type of ifstream
).
Additionally, and you probably already know this, you can pass a pointer/reference to an ifstream
to any function accepting a pointer/reference to a istream
. For example, the following is allowed by the language:
void processStream(const std::istream& stream);
std::ifstream* myStream;
processStream(*myStream);
std::istream *istreamObj = dynamic_cast<std::istream *>(&ifStreamObj)
No cast is necessary.
#include <fstream>
int main()
{
using namespace std;
ifstream f;
istream& s = f;
}