Previous section   Next section

Imperfect C++ Practical Solutions for Real-Life Programming
By Matthew Wilson
Table of Contents
Part Five.  Operators


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 it's appropriate. Sometimes we can return an instance of a simple class by value, and want to have it "be" or "not be" rather than having to throw an exception. Whatever the motivation, not to mention the rights or wrongs of the matter, you'll come across such things quite often, and will occasionally want to provide such behavior for your own classes.


      Previous section   Next section