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();
}
  1. A. 2 1
  2. B. 2 2
  3. C. 1 1
  4. 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

Exams that ask this topic