Q: operator void* or operator bool?

J

Jakob Bieling

Hi,

I remember reading a document that advised to prefer 'operator void*'
over 'operator bool' or other way round, when I want to provide the ability
to use code like this:

test_class t;
while (t)
{
// do stuff
};

But I cannot remember why and which method was prefered.

Thanks for the help!
 
L

Leor Zolman

Hi,

I remember reading a document that advised to prefer 'operator void*'
over 'operator bool' or other way round, when I want to provide the ability
to use code like this:

test_class t;
while (t)
{
// do stuff
};

But I cannot remember why and which method was prefered.

Thanks for the help!

To quote from Eckel/Allison's "Thinking in C++ Volume Two: Practical
Programming" (the footnote on page 167):

"It is customary to use operator void *() in preference to operator bool()
because the implicit conversions from bool to int may cause surprises,
should you incorrectly place a stream in a context where an integer
conversion can be applied. The operator void*() function will only be
called implicitly in the body of a Boolean expression."


Leor Zolman
BD Software
(e-mail address removed)
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
 
R

Rob Williscroft

Jakob Bieling wrote in
Hi,

I remember reading a document that advised to prefer 'operator
void*'
over 'operator bool' or other way round, when I want to provide the
ability to use code like this:

test_class t;
while (t)
{
// do stuff
};

But I cannot remember why and which method was prefered.

Well Leor's answered that, but if you want some extra safety:

#include <iostream>
#include <ios>

struct bool_as_member_helper
{
int i;
};
typedef int (bool_as_member_helper::*bool_as_member_ptr);


struct example
{
operator bool_as_member_ptr ()
{
return condition ? &bool_as_member_helper::i : 0;
}
bool condition;
};

struct bad
{
operator void * () { return 0; }
};

int main()
{
using namespace std;

cerr << boolalpha;

example ex = { false };

cerr << ex << '\n';
cerr << ( ex ? "? True\n" : "? False\n" );

ex.condition = true;

cerr << ex << '\n';
cerr << ( ex ? "? True\n" : "? False\n" );

cerr << "void * (boolalpha):\n" << bad() << '\n';
}

This method also avoid's the unwanted conversion to void *.

Rob.
 

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

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top