Search code examples
c++classoperator-overloadingconstantsconversion-operator

Integer cast overload being used instead of bool cast overload


I want to check if something is valid using bool cast overload:

Menu::operator bool() const {
        bool empty = false;
        if (m_title == nullptr) {
            empty = true;
        }

        return empty;
    }

However when I used

if (Menu1) { cout << "valid"; }

It used int cast overload instead

Menu::operator int()
    {
        int choice = option(); 
        return choice;
    }

Solution

  • It seems that the object Menu1 is not a constant object. So to call the conversion operator to bool, one conversion to const is required, while to call the conversion operator to int, no conversion to const is required.

    Declare both operators as constant member functions, and make them (or at least the conversion operator to int) explicit, as it is shown in the demonstrative program below:

    #include <iostream>
    
    struct A
    {
        int x = 0;
    
        explicit operator int() const 
        { 
            std::cout << "operator int() const is called\n";
            return x; 
        }
    
        explicit operator bool() const 
        { 
            std::cout << "operator bool() const is called\n";
            return x != 0; 
        }
    };
    
    int main() 
    {
        A a = { 10 };
    
        if ( a ) std::cout << a.x << '\n';
    
        return 0;
    }
    

    The program output is:

    operator bool() const is called
    10