Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
like image 771
ivivjcb Avatar asked Mar 02 '23 16:03

ivivjcb


1 Answers

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
like image 60
Vlad from Moscow Avatar answered Apr 06 '23 00:04

Vlad from Moscow