Why istream object can be used as a bool expression?

It's a cast operator to the given type. operator T () is a cast operator to the type T. In the if statement, the ifstream is converted to void*, and then the void* converted to bool.


The exact mechanism that enables use of an istream as a boolean expression, was changed in C++11. Previously is was an implicit conversion to void*, as you've found. In C++11 it is instead an explicit conversion to bool.

Use of an istream or ostream in a boolean expression was enabled so that C++ programmers could continue to use an expression with side-effects as the condition of a while or for loop:

SomeType v;

while( stream >> v )
{
    // ...
}

And the reason that programmers do that and want that, is that it gives more concise code, code that is easier to take in at a glance, than e.g. …

for( ;; )
{
    SomeType v;
    
    stream >> v;
    if( stream.fail() )
    {
        break;
    }
    // ...
}

However, in some cases even such a verbose structure can be preferable. It depends.