Previous section   Next section

Imperfect C++ Practical Solutions for Real-Life Programming
By Matthew Wilson
Table of Contents
Chapter 24.  operator bool()


24.3. operator bool() const

Since the operator we're after is logically representing a Boolean, what better to have than operator bool() const?



class ExpressibleThing


{


public:


  operator bool() const;


};



This is the approach commonly taken since the bool type was introduced in C++-98. Unfortunately, bool is implicitly convertible to int, so we've still got the integral promotion problems we saw in section 24.1, so that ExpressibleThing can take part in arithmetic expressions, as in:



ExpressibleThing  et1;


ExpressibleThing  et2;


int               nonsense = et1 + et2;



But there's worse news. All of our three solutions so far return a basic, publicly accessible, type, either int, void (const)*, or bool. This means that the types can take part in erroneous equality comparisons with any other type that provides conversions to our type's "Boolean" type, or any type to which that might be converted. Consider the following scary bunch of code:



class SomethingElseEntirely


{


public:


  operator bool() const;


};





SomethingElseEntirely set;


ExpressibleThing      et;





if(set == et)


{


  . . .



This is really not good.


      Previous section   Next section