Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When an object provides both `operator!` and `operator bool`, which is used in the expression `!obj`?

I've ran across a question I am not able to answer for myself. Also, I didn't find an answer to this on both google and here. Say, I want to "check an object for validity" in an if clause, like so:

MyClass myObject;

// [some code, if any]

if (!myObject)
{
    // [do something]
}

Let MyClass be defined something like this:

class MyClass
{
public:
    MyClass() { };
    virtual ~MyClass() { };
    bool operator!()
    {
        return !myBool;
    };
    operator bool()
    {
        return myBool;
    };
private:
    bool myBool = 0;
};

My question now is: Which one of the overloaded operators is actually used in this if clause? Either way, the result is obviously the same.

like image 453
poljpocket Avatar asked Dec 19 '13 14:12

poljpocket


2 Answers

It will use operator!.

A function whose parameter types match the arguments will be chosen in preference to one that requires type conversions.

like image 151
Mike Seymour Avatar answered Oct 31 '22 15:10

Mike Seymour


You'll find that operator ! gets executed because it's the most direct resolution. If it used operator bool instead then it would have to call the conversion operator first, and then apply the ! separately to that.

As a general rule, it's a good idea to avoid that situation though. It's generally better just to define the bool conversion, because strictly speaking that's what you want your logical operators to act on, rather than MyClass directly. Defining both creates a bit of a readability problem, and is a form of redundant code duplication (which can lead to programmer error in future).

like image 40
Peter Bloomfield Avatar answered Oct 31 '22 16:10

Peter Bloomfield