c++c++11operator-overloadinglogical-operatorsnegation

Should operator !() be defined in a class if bool() operator is already defined?


I have a simple class which is a concrete class and is not designed to be inherited. Also I want to be able to say !myobject where myobject is an instance of this class. I've already define operator bool(). Should I also define bool operator!()?

Here is trivial example of the class:

class Test
{
  public:
    ...
    explicit operator bool() {
      return error_ == 0;
    }

    bool operator!() {
      return error_ != 0;
    }

  private:
    int error_;
};

I tried it as !myobject and it works independent of !() operator is being defined or not. Looks like it is a silly question, but I couldn't find an answer for it.


Solution

  • According to the C++ 17 Standard (8.3.1 Unary operators)

    9 The operand of the logical negation operator ! is contextually converted to bool (Clause 7); its value is true if the converted operand is false and false otherwise. The type of the result is bool.

    So there is no need to overload the operator !() when there is the conversion operator to the type bool.