By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,238 Members | 1,804 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,238 IT Pros & Developers. It's quick & easy.

how to overload an operator to assert object as boolean value ? (not !())

P: n/a
Hello,

Sometimes it is desired to assert an object as boolean value, e.g.

class A{
};
.......

A a;
while(a=next()){
.......
}

i have learnt that the operator !() could be overloaded to simulate the
bahaviour,
nevertheless in various situations it makes more sense to assert an object
directly
(like a pointer does), using !() make it a bit awkward ...

Br,Kai
Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
class Test
{
bool value;

public:

Test() : value(true)
{}

operator bool()
{
return value;
}
};

Be careful though, it might catch you unaware some times..

Regards
Senthil

Jul 23 '05 #2

P: n/a
"sadhu" <se**********@wdevs.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
class Test
{
bool value;

public:

Test() : value(true)
{}

operator bool()
{
return value;
}
};

The danger with that is that suddenly the following
statements become valid as well:
Test t;
int a = t; // yes, bool can convert to an int...

A better way is replace the bool conversion with:
operator const volatile void* ()
{ return value ? this : 0; }
This still allows you to write if( t ) , but is
less prone to unexpected conversions.

Even safer is to provide a conversion to a member
function pointer type... but this gets a bit ugly IMHO.
For myself, I prefer to only implement the ! operator,
and to write if( !! t ) - because I normally use
the !! operator to make conversions to bool explicit.
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- e-mail contact form
Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.