unvadim unvadim - 3 years ago 89
C++ Question

bool vs void* casts on the same object

The code below prints 'operator bool' when used in the if statement and 'operator void*' when it needs a bool for function call.

Why isn't it using

operator bool
for the function call too? And how to make it use it in both cases?

#include <iostream>

class A
{
public:
explicit operator bool() const
{
std::cout << "operator bool" << std::endl;
return true;
}

operator void*() const
{
std::cout << "operator void*" << std::endl;
return 0;
}
};

void f(bool valid)
{
std::cout << "f called " << valid << std::endl;
}

int main(int argc, char *argv[])
{
A a;

if(a)
std::cout << "if a" << std::endl;

f(a);

return 0;
}

Answer Source

In an if statement, implicit and explicit conversion operators are considered. Because A has an operator bool, it chooses that one, as it is a better match than converting A to a void* and then converting that to bool.

But in every other statement, which are not conditions (if, while, ...), the explicit conversion operators do not participate in overload resolution, and the only valid operator then is operator void*, which can be used because there is an implicit conversion from pointers to bool.

If you want operator bool to be selected, you need make it non-explicit, or use a cast (because that's what marking it explicit means, making sure that one has to be explicit to use it):

f(static_cast<bool>(a));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download