c++operatorsimplicit-conversionconversion-operator

What is the meaning of "operator bool() const"


For example:

operator bool() const 
{ 
    return col != 0; 
}

col is an int. How does operator bool() const work?


Solution

  • Member functions of the form

    operator TypeName()
    

    are conversion operators. They allow objects of the class type to be used as if they were of type TypeName and when they are, they are converted to TypeName using the conversion function.

    In this particular case, operator bool() allows an object of the class type to be used as if it were a bool. For example, if you have an object of the class type named obj, you can use it as

    if (obj)
    

    This will call the operator bool(), return the result, and use the result as the condition of the if.

    It should be noted that before C++11, operator bool() is A Very Bad Idea. For a detailed explanation as to why it is bad and for the solution to the problem, see "The Safe Bool Idiom."

    C++11 adds support for explicit conversion operators. These allow you to write a safe explicit operator bool() that works correctly without having to jump through the hoops of implementing the Safe Bool Idiom.