ProgrammingVery hardProduct company interview · GATE level

Which lines fail to compile?

Which lines fail to compile?
struct A { explicit A(int) { } };
struct B { B(int) { } };
void takeA(A) { }
void takeB(B) { }
int main() {
    A a1(5);        // L1
    A a2 = 5;       // L2
    B b1 = 5;       // L3
    takeA(5);       // L4
    takeB(5);       // L5
    A a3 = A(5);    // L6
    takeA({5});     // L7
}
  1. A. L2, L4 and L7
  2. B. L2 and L4
  3. C. L2, L4, L6 and L7
  4. D. L4 and L7

Correct answer: A. L2, L4 and L7

An explicit constructor can be used only for direct initialisation (L1) or in an explicit conversion (L6, A(5)). Copy initialisation from an int - A a2 = 5 and passing 5 to a parameter of type A - needs an implicit conversion, so L2 and L4 fail. Copy-list-initialisation (L7, passing {5}) also may not choose an explicit constructor. B's constructor is not explicit, so L3 and L5 compile.

More OOP with C++ and Java questions

Exams that ask this topic