I have a function call to some_func that takes int as argument.
int some_func(int);
class S {
public:
S(int v) {
a = v;
}
...
operator bool() const {
return true;
}
int a;
}; // class S doesn't define any "operator int"
S obj;
int x = some_func(obj); // some_func expected an int argument
In the above code, some_func expected int argument but is called with an object of type S. So it needs to convert it to "int".
But why is it using "operator bool"? Shouldn't it produce compile error saying no correct conversion method to int is specified for class S?
If I remove operator bool definition, then the program doesn't compile and gives an error about argument type mismatch in some_func call.
boolvalue is implicitly convertible to anintwith the value0(forfalse) or1(fortrue). See e.g. this implicit conversion reference (especially the section about integral promotion) for more information. - Some programmer dudeexplicit operator bool()- available since C++11. - zett42