With all of the fundamental types of C++, one can simply query:
if(varname)
and the type is converted to a boolean for evaluation. Is there
You can define a user-defined conversion operator. This must be a member function, e.g.:
class MyClass {
operator int() const
{ return your_number; }
// other fields
};
You can also implement operator bool. However, I would STRONGLY suggest against doing it because your class will become usable in arithmetic expressions which can quickly lead to a mess. IOStreams define, for example, conversion to void*
. You can test void*
in the same way you can test a bool
, but there are no language-defined implicit conversions from void*
. Another alternative is to define operator!
with the desired semantics.
In short: defining conversion operator sto integer types (including booleans) is a REALLY bad idea.