How do I override the bool operator in a C++ class?
Well, you could overload operator bool()
:
class ReturnValue
{
operator bool() const
{
return true; // Or false!
}
};
overload this operator:
operator bool();
The simple answer is providing operator bool() const
, but you might want to look into the safe bool idiom, where instead of converting to bool (which might in turn be implicitly converted to other integral types) you convert to a different type (pointer to a member function of a private type) that will not accept those conversions.
It's better to use explicit keyword or it will interfere with other overloads like operator+
Here is an example :
class test_string
{
public:
std::string p_str;
explicit operator bool()
{
return (p_str.size() ? true : false);
}
};
and the use :
test_string s;
printf("%s\n", (s) ? s.p_str.c_str() : "EMPTY");