4

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

user2321876
  • 105
  • 1
  • 8
  • 2
    It's is supposed to compile, that's a context that is considered "explicit". – Mat Aug 18 '13 at 21:02
  • 1
    You'll find relevant posts by searching for "[c++] contextually converted bool" (without the quotes) – Mat Aug 18 '13 at 21:08
  • 2
    What are the contexts that are considered "explicit" where I can find some information about this ? – user2321876 Aug 18 '13 at 21:09

1 Answers1

3

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.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982