Chapter 24. operator bool()

We saw in section 13.4.2 that conditional expressions are translated to an integral form (int in C; bool in C++) before evaluation. C and C++ are capable of applying implicit conversions from a variety of scalar types (see Prologue), including pointers, which allows for the somewhat useful constructs such as:

void *p = . . .;

if(p)   // Evaluates whether p is the null pointer
{}
if(!p)  // Evaluates whether p is not the null pointer
{}

There are occasions when it is necessary to allow instances of user-defined types to do the same. A good example is the idiomatic IOStreams extraction loop:

while(std::cin  name  salary)
{
  . . .
}

Smart pointers, such as std::auto_ptr, are another example, but there are many other cases where ...

Get Imperfect C++ Practical Solutions for Real-Life Programming now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.