Operator overloading on "default" operator

J

John Smith

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.

Thanks in advance.
-- John
 
K

Karl Heinz Buchegger

John said:
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.

Thanks in advance.
-- John

class A
{

operator bool() { /* do whatever you need to do and return
a boolean value */ }
};
 
I

Ivan Vecerina

Karl Heinz Buchegger said:
....
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,733
Messages
2,569,439
Members
44,829
Latest member
PIXThurman

Latest Threads

Top