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

Viewed 134

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.

2 Answers
Related