ProgrammingVery hardProduct-company MCQ pattern
What is printed?
What is printed?
struct A {
int v = 1;
virtual void show() { cout << v; }
};
struct B : A {
int v = 2;
void show() override { cout << v << " "; A::show(); }
};
int main() {
A *p = new B;
p->show();
}- A. 2 1
- B. 2 2
- C. 1 1
- D. 1 2
Correct answer: A. 2 1
show() is virtual, so p->show() dispatches to B::show at runtime. Inside it, the unqualified v refers to B's own member (2). The explicit A::show() call then runs the base version, where its unqualified v is resolved statically to A's own member (1), since fields are never virtual.
More OOP with C++ and Java questions
- What is printed? cpp struct Base { virtual void f() { cout << "Base-f "; g(); } void g() { cout << "Base-g"; } }; struct Derived : Base {…
- What is printed? java class A { static { System.out.print("A-static "); } } class B extends A { static { System.out.print("B-static "); }…
- What is printed? java class Parent { int bonus() { return 10; } } class Child extends Parent { static int bonus(int n) { return n + 1; } }…
- What is printed? java class A { { System.out.print("IB-A "); } A() { System.out.print("CTOR-A "); } } class B extends A { {…
- What is printed? cpp void f(int x) { cout << "int"; } void f(double x) { cout << "double"; } int main() { f('a'); }
- What happens when this is compiled? java class A { final void m() { System.out.println("A"); } } class B extends A { void m() {…