Code:
#include <iostream>
using namespace std;
#define B2T( var ) (var ? "true" : "false")
class CExample
{
private:
bool m_bValid;
public:
CExample( bool bValid )
{
cout << "constructor: " << B2T( bValid ) << endl;
m_bValid = bValid;
}
operator bool ()
{
cout << "typecast to bool" << endl;
return m_bValid;
}
};
int main()
{
CExample ex( true ); // switch this line to "false" for testing reverse
cout << "explicitly typecasted ex is " << B2T( (bool)ex ) << endl;
cout << "implicitly typecasted ex is " << B2T( ex ) << endl;
if( ex )
{
cout << "ex evaluated to true in if() construct" << endl;
}
else
{
cout << "ex evaluated to false in if() construct" << endl;
}
return 0;
}
If you implement a typecast operator for bool, it will work the way you want it. Note that you might get in trouble when you implement an operator that also casts to an integer value ( void*, int, long, char ) because the compiler might chose another implicit conversion. Naturally this will occur at the most unpleasant time possible, deadline near or over, valentines day without a gift yet and running out of coffee. It is possible as outlined above, but it will bite you in your behind when you expext it least. Go the boring but safe way and implement an IsValid() method.
btw: the B2T macro is just for output candy, you can remove it if 0 for false and 1 for zero are okay for you, the example will work the same.