Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I override the bool operator in a C++ class?

Tags:

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?

like image 886
Josh Glover Avatar asked Apr 29 '11 07:04

Josh Glover


People also ask

Can we override operator?

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.

How do you overload the operator?

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.

How do you overload a comparison operator?

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.

Can override number of operands of an operator?

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.


2 Answers

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.

like image 154
David Rodríguez - dribeas Avatar answered Sep 18 '22 20:09

David Rodríguez - dribeas


Well, you could overload operator bool():

class ReturnValue
{
    operator bool() const
    {
        return true; // Or false!
    }
};
like image 28
Oliver Charlesworth Avatar answered Sep 21 '22 20:09

Oliver Charlesworth