Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ operator overloading, operator bool() and operator !()

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


1 Answers

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.

like image 166
Ben Voigt Avatar answered Nov 01 '25 15:11

Ben Voigt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!