Consider the following short C++ program:
#include
class B {
public:
operator bool() const {
return false;
}
};
class B2 : pub
The C++ bool type has two values - true and false with corresponding values 1 and 0. The inherent confusion can be avoided if you add a bool operator in B2 class that calls base class(B)'s bool operator explicitly, then the output comes as false. Here's my modified program. Then operator bool means operator bool and not operator int by any means.
#include
class B {
public:
operator bool() const {
return false;
}
};
class B2 : public B {
public:
operator int() {
return 5;
}
operator bool() {
return B::operator bool();
}
};
int main() {
B2 b;
std::cout << std::boolalpha << (bool)b << std::endl;
}
In your example, (bool) b was trying to call the bool operator for B2, B2 has inherited bool operator, and int operator, by dominance rule, int operator gets called and the inherited bool operator in B2. However, by explicitly having a bool operator in B2 class itself, the problem gets solved.