How do I override the bool operator in a C++ class?

32,532

Solution 1

The simple answer is providing operator bool() const, but you might want to look into the safe bool idiom, where instead of converting to bool (which might in turn be implicitly converted to other integral types) you convert to a different type (pointer to a member function of a private type) that will not accept those conversions.

Solution 2

Well, you could overload operator bool():

class ReturnValue
{
    operator bool() const
    {
        return true; // Or false!
    }
};

Solution 3

It's better to use explicit keyword or it will interfere with other overloads like operator+

Here is an example :

class test_string
{
public:
   std::string        p_str;

   explicit operator bool()                  
   { 
     return (p_str.size() ? true : false); 
   }
};

and the use :

test_string s;

printf("%s\n", (s) ? s.p_str.c_str() : "EMPTY");

Solution 4

overload this operator:

operator bool();
Share:
32,532
Josh Glover
Author by

Josh Glover

A Lisp fanatic hacking Clojure in Stockholm.

Updated on July 09, 2022

Comments

  • Josh Glover
    Josh Glover almost 2 years

    I'm defining a ReturnValue class in C++ that needs to report whether a method was successful. I want objects of the class to evaluate to true on success and false on error. Which operator do I override to control the truthiness of my class?

  • Bo Persson
    Bo Persson almost 13 years
    And if you use the very latest compilers, you can use the new C++0x feature explicit operator bool() to avoid the implicit conversions.
  • Josh Glover
    Josh Glover almost 13 years
    Very nice! I'll probably go with the easy operator bool() const in my current use case, just for simplicity's sake, but the safe bool idiom seems much more suitable for real production code. It is kind of sad that C++ forces you into craziness like this, though. :-/
  • Josh Glover
    Josh Glover almost 13 years
    @Bo, as luck would have it, since this is a personal project, I get to choose my compiler, and GCC 4.5 supports this. Thanks!
  • Josh Glover
    Josh Glover almost 13 years
    @Bo, if you make this an answer, I'll accept it, as it is certainly the nicest way to handle truthiness for a class. Oh, and greetings from Stockholm! :)
  • Andreas Spindler
    Andreas Spindler over 2 years
    Consider explicit operator bool() const noexcept.