ProgrammingVery hardProduct-company placement · C++
Which line fails to compile?
Which line fails to compile?
struct A { A(int) { } };
struct B { explicit B(int) { } };
A f() { return 5; } // L1
B g() { return 5; } // L2
B h() { return B(5); } // L3- A. L2 only
- B. L1 and L2
- C. L3 only
- D. None
Correct answer: A. L2 only
return expr copy-initialises the return value, so it can use a converting constructor (L1) but not an explicit one (L2). Constructing B explicitly (L3) is fine.
More OOP with C++ and Java questions
- Which line fails to compile? cpp int main() { int a[3] = {1, 2, 3}, b[3]; b = a; // L1 array<int, 3> c{1, 2, 3}, d; d = c; // L2 }
- What is printed? cpp template <sizet N> sizet len(int (&)[N]) { return N; } int main() { int a[7]; cout << len(a); // L1 int p = a; cout…
- What is printed? cpp struct S { void f() & { cout << "L"; } void f() && { cout << "R"; } }; int main() { S s; s.f(); S().f()…
- What is printed? cpp int main() { int x = 0; auto f = [x]() mutable { return ++x; }; f(); f(); cout << f() << x; }
- What is printed? cpp int main() { std::function<int()> f; try { cout << f(); } catch (const badfunctioncall&) { cout << "E"; } }
- What is printed? cpp struct W { W(int, int) { cout << "2"; } W(initializerlist<int>) { cout << "L"; } }; int main() { W a(1, 2); W b{1…