tags:

views:

67

answers:

2

Hello!

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?

A: 

Try file.good() or cast the file to bool:

file.open("no such file");
if (file)
  cout << "Open OK" << endl;
else
  cout << "Open FAILED" << endl;
kyku
Thank You, but I am not trying to check the return value. I am curious about the fact that I am seemingly calling a function on a null object, which is unusual in other languages.
zoul
+3  A: 

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

cout << file << endl;

the compiler converts this to:

cout << file.operator void*() << endl;

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:

(file == NULL)

You compare the zero returned by operator void*() zero with NULL and get 1.

anon
Ah. And I event tried static_cast to void* to see if there is some overloading magic hidden behind the scene! Apparently there was even more magic than I expected. Thank You.
zoul