I have got the following sample:
#include <iostream> #include <fstream> using namespace std; int main() { ifstream file; cout << file << endl; // 0xbffff3e4 file.open('no such file'); cout << file << endl; // 0 cout << (file == NULL) << endl; // 1 cout << file.fail() << endl; // 1 }
If the file is NULL, how is it possible to call the fail member function? I am not very familiar with C++, is this normal behaviour? What am I getting wrong here?
file is an object – it cannot be null. However, ifstream has an operator void*() overload which returns 0 when the file is in a bad state. When you say (for example):
the compiler converts this to:
This conversion will be used in all sorts of places – basically anywhere that a pointer or integer type could be used. It is used when you say:
You compare the zero returned by operator void*() zero with NULL and get 1.