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();
}- A. 10 10
- B. 20 20
- C. 10 20
- 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
- What is printed? java class Util { static int counter = 0; static void inc() { counter++; } } class UtilChild extends Util { } public…
- What is printed? cpp struct Base { static int count; Base() { count++; } }; int Base::count = 0; struct Derived : Base {}; int main() {…
- What is printed? java interface Shape { static double unit() { return 1.0; } double area(); } class Square implements Shape { double side…
- What is printed? cpp struct Counter { static int next() { static int n = 0; return ++n; } }; int main() { cout << Counter::next() <<…
- What is printed? cpp class Account { double balance; public: Account(double b) : balance(b) {} Account operator+(const Account &other)…
- What is printed? java class Base { public static void greet() { System.out.print("Base.greet "); } } class Sub extends Base { public…