ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
struct A {
    int x = 10;
    virtual int getX() { return x; }
};
struct B : A {
    int x = 20;
    int getX() override { return x; }
};
int main() {
    A *a = new B();
    cout << a->x << " " << a->getX();
}
  1. A. 10 10
  2. B. 20 20
  3. C. 10 20
  4. D. 20 10

Correct answer: C. 10 20

a->x is a plain (non-virtual) member access resolved by the pointer's static type A, giving A::x = 10. a->getX() is a virtual call resolved by the real object's type, B, returning B::x = 20. C++ fields and Java fields behave the same way here: no field polymorphism, only (virtual) method polymorphism.

More OOP with C++ and Java questions

Exams that ask this topic