Why implicit conversion is occurring in "if expression" although it should be explicit conversion

StackOverflow https://stackoverflow.com/questions/18303568

  •  24-06-2022
  •  | 
  •  

Question

This code is not supposed to compile , so why it is ? what is the principle of the context in if expression ?

class B {  
public:  
    B() {}  
    explicit operator bool () {}  
};  



int main (){  
    B Bp;  
  //bool check = Bp // error
    if (Bp){   //o.k
        return 1;  
    }  
    return 0;  
}  

Thanks

Was it helpful?

Solution

That code very much is supposed to compile. The standard expended a very great deal of effort to ensure that it does.

There are a number of places where an expression is "contextually converted to bool" In those places, explicit bool conversions will be called if they're available. One of those contextual conversions is the if expression, as in your case.

This language allows explicit operator bool types to still be used for conditional checking if(expr), but you can't other things without an explicit conversion. You can't pass it to a function that takes a bool; you can't return it from a function that returns bool, and so forth.

All of the contextual conversions are explicit expressions in language features. So explicit operator bool protects you from implicit user-defined conversions, while still allowing language-defined conversions to happen.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top