I've ran across a question I am not able to answer for myself. Also, I didn't find an answer to this on both google and here. Say, I want to "check an object for validity" in an if clause, like so:
MyClass myObject;
// [some code, if any]
if (!myObject)
{
// [do something]
}
Let MyClass
be defined something like this:
class MyClass
{
public:
MyClass() { };
virtual ~MyClass() { };
bool operator!()
{
return !myBool;
};
operator bool()
{
return myBool;
};
private:
bool myBool = 0;
};
My question now is: Which one of the overloaded operators is actually used in this if clause? Either way, the result is obviously the same.
It will use operator!
.
A function whose parameter types match the arguments will be chosen in preference to one that requires type conversions.
You'll find that operator !
gets executed because it's the most direct resolution. If it used operator bool
instead then it would have to call the conversion operator first, and then apply the !
separately to that.
As a general rule, it's a good idea to avoid that situation though. It's generally better just to define the bool
conversion, because strictly speaking that's what you want your logical operators to act on, rather than MyClass
directly. Defining both creates a bit of a readability problem, and is a form of redundant code duplication (which can lead to programmer error in future).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With