ProgrammingModerateProduct-company placement · C++
Which line fails to compile?
Which line fails to compile?
struct B { virtual B* clone() { return new B; } virtual int id() { return 1; } };
struct D : B {
D* clone() override { return new D; } // L1
long id() override { return 2; } // L2
};- A. L1 only
- B. Both
- C. L2 only
- D. Neither
Correct answer: C. L2 only
Return types may be covariant only for pointers or references to classes (B* → D*). Changing int to long is not allowed for an overriding function.
More OOP with C++ and Java questions
- What is printed when compiled as C++17? cpp struct A { A() { cout << "D"; } A(const A&) { cout << "C"; } }; int main() { A a = A(A()); }
- What is printed? cpp struct B { B& operator=(int) { cout << "B"; return this; } }; struct D : B { }; int main() { D d; d = 5; }
- What is printed? cpp template <typename T> struct Box { static int count; Box() { count++; } }; template <typename T> int Box<T>::count =…
- What is printed? cpp struct N { int v; N(int x = 7) : v(x) { } }; void show(N n) { cout << n.v; } int main() { N a; N b = 3; show(4)…
- What is printed? java class P { void f(int x) { System.out.print("P-int "); } } class C extends P { void f(long x) {…
- What is printed? java BigDecimal a = new BigDecimal("1.0"), b = new BigDecimal("1.00"); Set<BigDecimal> h = new HashSet<>(List.of(a, b))…