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.Qaz– Qaz2012-12-09 01:53:03 +00:00Commented Dec 9, 2012 at 1:53
-
1See also this stack overflow question and answer stackoverflow.com/questions/4600295/…Richard Chambers– Richard Chambers2012-12-09 01:55:36 +00:00Commented Dec 9, 2012 at 1:55
-
1this article about using operator bool and operator ! may also be helpful. artima.com/cppsource/safebool.htmlRichard Chambers– Richard Chambers2012-12-09 02:03:14 +00:00Commented Dec 9, 2012 at 2:03
1 Answer
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.