@ndcn541,
C & C++ "if" statements evaluate a boolean. Whatever expression is inside the parenthesis must resolve to a boolean for "if" to work, notwithstanding the multiple tests possible, like if ( a < b || b > d ).
So, if you want to be able to evaluate an instance with
You would add a conversion operator representing a boolean.
1 2 3 4 5 6 7 8
|
class A
{
private:
int v { 0 };
public:
operator bool () const { if ( v > 0 ) return true; return false; }
};
|
That trivial example will permit an instance of class A to be evaluated as a bool, using a conversion operator. Of course, there still must be some kind of evaluation in the conversion operator which makes sense, which follows what @zapshe is saying where the "set" member provides a true or false value, but that could be wrapped up into a conversion operator to bool.
There is a problem, though. Some conversions happen when you don't expect it. Wherever a function overload calls for a bool and can take an "A", there can be conflicts which cause the compiler to complain.
You can precede the conversion operator with the "explicit" declaration, which can help.
From a design standpoint it isn't advisable to do this just for convenience. It should be a design concern that evaluating the instance as a bool makes sense due to what the object is and does.
For example, there is a conversion operator available so you can evaluate some smart pointers as bools, to test if they're "nullptr", or contain some valid instance. This mimics historical use of raw pointers in the same test, which makes sense as a design.
On the other hand, if you design a class representing a 2d vector (as in graphics, not containers), and you must test to ensure the vector is a unit vector (length of 1), using a conversion operator so this vector could be tested as a bool doesn't make sense, because there are no other situations in which vectors are tested this way in math. To evaluate if a vector is a unit vector, it should be checked for it's length == 1, so one should make that explicit by using the length() member function of a vector. There could be so many different interpretations for a conversion to bool on a vector (like, a zero vector), that it just doesn't "fit" well to use the one and only conversion operator to a bool for some arbitrary choice.