I'm defining a ReturnValue
class in C++ that needs to report whether a method was successful. I want objects of the class to evaluate to true
on success and false
on error. Which operator do I override to control the truthiness of my class?
You can override operators, but they might not do what you want. The reason is that operators (actually overloads in general) are selected from the static type of an object. If you now have a reference-to-base which is bound to a derived instance, it will not call the operator for the derived class.
To overload an operator, we use a special operator function. We define the function inside the class or structure whose objects/variables we want the overloaded operator to work with.
The comparison operators (<, <=, >, >=, == and !=) can be overloaded by providing definition to __lt__, __le__, __gt__, __ge__, __eq__ and __ne__ magic methods. Following program overloads == and >= operators to compare objects of distance class.
You cannot change the precedence, grouping, or the number of operands of an operator. An overloaded operator (except for the function call operator) cannot have default arguments or an ellipsis in the argument list.
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.
Well, you could overload operator bool()
:
class ReturnValue
{
operator bool() const
{
return true; // Or false!
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With