ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
struct A {
virtual void f() { std::cout << "A::f "; }
};
struct B : A {
void f() override { std::cout << "B::f "; }
void f(int x) { std::cout << "B::f(int) " << x; }
};
int main() {
B b;
A &ra = b;
ra.f();
}- A. Compilation error: ambiguous between f() and f(int)
- B. B::f(int) 0
- C. A::f
- D. B::f
Correct answer: D. B::f
Through ra (static type A&), only A's interface is visible for overload resolution, which has exactly one f() taking no arguments. That resolves to the f() slot, and virtual dispatch sends it to B's override at runtime: B::f.
More OOP with C++ and Java questions
- Which statement about this program's behaviour is true? cpp struct S { int b; int a; S() : a(1), b(a + 1) { } }; int main() { S s…
- What is printed? java class A { protected int val() { return 1; } } class B extends A { protected int val() { return 2; } } class C…
- A Java class's constructor runs this.handle = acquire(); and then later throws an exception before returning. Which statement is correct?
- What is printed? cpp struct N { int v; N(int x) : v(x) { std::cout << "N" << v << " "; } ~N() { std::cout << "~N" << v << " "; } }; int…
- What is printed? java class A { public String toString() { return "A"; } } class B extends A { public String toString() { return "B-" +…
- What is printed? java class Box<T> { T value; } // in main: Box<String> b1 = new Box<>(); Box<Integer> b2 = new Box<>()…