ProgrammingVery hardProduct-company placement · C++

Which lines fail to compile?

Which lines fail to compile?
struct F { explicit operator bool() const { return true; } };
int main() {
    F f;
    if (f) cout << "Y";                 // L1
    bool b = f;                         // L2
    bool c = static_cast<bool>(f);      // L3
    int n = f + 1;                      // L4
    bool d = !f;                        // L5
}
  1. A. L2, L4 and L5
  2. B. L4 only
  3. C. L2 and L4
  4. D. L1, L2 and L4

Correct answer: C. L2 and L4

An explicit conversion to bool is still used in 'contextual' boolean conversions: if, !, &&, ||, ?:. Copy-initialising a bool or using f in arithmetic needs an implicit conversion, which explicit forbids.

More OOP with C++ and Java questions

Exams that ask this topic