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
}- A. L2, L4 and L5
- B. L4 only
- C. L2 and L4
- 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
- What is printed? cpp struct M { operator int() const { return 7; } }; int main() { M m; cout << m + 1; }
- What is printed? cpp // C++17 struct Counter { int n = 0; int operator()() { return ++n; } }; int main() { Counter c; c(); c(); Counter d…
- Which line fails to compile? cpp class B { public: void f() { cout << "f"; } void g() { cout << "g"; } }; class D : private B { public…
- What is printed? cpp struct A { void hi() { cout << "A"; } }; struct B { void hi(int) { cout << "B"; } }; struct C : A, B { }; int main()…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B { virtual void f() { cout << "B"; } }; struct C : A, B {…
- How many of these statements about C++ are correct? (i) A constructor cannot be declared virtual. (ii) A static member function cannot be…