4

If I have overloaded operator bool(). Do I need to overload operator !() too? When and why. Thanks for help.

3
  • When there's more than one user-defined conversion maybe, but that's easily fixed without doing that. Commented Dec 9, 2012 at 1:53
  • 1
    See also this stack overflow question and answer stackoverflow.com/questions/4600295/… Commented Dec 9, 2012 at 1:55
  • 1
    this article about using operator bool and operator ! may also be helpful. artima.com/cppsource/safebool.html Commented Dec 9, 2012 at 2:03

1 Answer 1

6

You should also implement operator!() if you want a developer to be able to say !myobject where myobject is an instance of your class.

Section 13.3.1.2 specifies that when applying a unary operator to an object of user-defined type

the built-in candidates include all of the candidate operator functions defined in 13.6 that, compared to the given operator,

  • have the same operator name, and
  • accept the same number of operands, and
  • accept operand types to which the given operand or operands can be converted according to 13.3.3.1, and
  • do not have the same parameter-type-list as any non-template non-member candidate.

So the compiler may use the built-in bool operator!(bool) and your user-defined conversion, but only when your operator bool() is implicitly callable. operator bool() is almost always made explicit to avoid its use in arbitrary integer contexts. Multiple user-defined conversions could also create ambiguity among built-in candidate operators as chris mentioned in a comment.

So it's best to just define operator!() yourself.

Sign up to request clarification or add additional context in comments.

1 Comment

thx @leftroundabout, I messed up the formatting there and didn't even notice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.