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
}- A. L2, L4 and L7
- B. L2 and L4
- C. L2, L4, L6 and L7
- 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
- What is printed? cpp struct N { int v = 0; N& operator++() { cout << "pre "; ++v; return this; } N operator++(int) { cout << "post "; N t…
- What is printed? java String s = "a,b,,c,,"; System.out.print(s.split(",").length);
- What is printed? java System.out.print(",x,".split(",").length + " " + "".split(",").length);
- What is printed? java String a = "Aa", b = "BB"; Set<String> set = new HashSet<>(); set.add(a); set.add(b); System.out.print((a.hashCode()…
- What is printed? java PriorityQueue<String> pq = new PriorityQueue<>( Comparator.comparing(String::length).thenComparing(Comparator.reverse…
- What is printed? java Set<String> s = new TreeSet<>(Comparator.comparingInt(String::length)); s.add("one"); s.add("two"); s.add("three")…