I have my class, where I overloaded the ! operator:
class obj
{
public:
bool operator!() const
{ return this->str.length() == 0; }
private:
string str;
};
With the ! operator i want to check the obj validity, so:
obj o;
// if o is not a valid object
if(!o)
cerr << "Error";
Now I want to have the possibility to do this:
// if o is a valid object
if(o)
cout << "OK";
How can I do?
Using C++11, you can do this by having an
explicit operator bool:This operator is called if you ever need to cast your object to a
boolexplicitly (which is done by theifstatement automatically). The implementation works by calling youroperator !on the receiver object, then returning the opposite result.Hope this helps!