4

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

  • When there's more than one user-defined conversion maybe, but that's easily fixed without doing that. – chris Dec 09 '12 at 01:53
  • 1
    See also this stack overflow question and answer http://stackoverflow.com/questions/4600295/what-is-the-meaning-of-operator-bool-const-in-c – Richard Chambers Dec 09 '12 at 01:55
  • 1
    this article about using operator bool and operator ! may also be helpful. http://www.artima.com/cppsource/safebool.html – Richard Chambers Dec 09 '12 at 02:03

1 Answers1

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.

leftaroundabout
  • 117,950
  • 5
  • 174
  • 319
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720