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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.