"Karl Heinz Buchegger" <kb******@gascad.at> wrote in message
news:41***************@gascad.at...
John Smith wrote:
Hello,
I made a class which works like bool primitive but has some special
properties.
Now I want to be able to overload an operator to be able to do the
following:
while (myObj)
{
...
}
It must return true/false naturally, but I'm unsure if it's actually
possible and if so which operator I should overload.
.... class A
{
public: // added for the sake of the discussion below operator bool() { /* do whatever you need to do and return
};
This is the "obvious" solution, but has well-known caveats,
because bool-s are implicitly convertible to int.
For example, the following expressions become valid:
A a;
int b = 5+a;
a << 5;
This is why usually library writers now prefer to provide
a conversion operator to void* or to a (member) function pointer.
For a discussion, see for example:
http://www.artima.com/cppsource/safebool.html
My personal preference, for internal code, is to implement
operator ! only, because I like to use !! to explicitly
convert values to bool -- e.g. I prefer if( !! myPtr )
to if( myPtr != NULL ) or if( myPtr ) .
Cheers,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form