ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
struct A { virtual void f() { cout << "A"; } };
struct B : A { virtual void f() { cout << "B"; } };
struct C : B { virtual void f() { cout << "C"; } };
int main() {
    A *p = new C();
    B *q = static_cast<B*>(p);
    q->f();
}
  1. A. A
  2. B. B
  3. C. C
  4. D. Compile-time error: static_cast cannot convert A* to B*

Correct answer: C. C

static_cast<B*>(p) just reinterprets the pointer's static type as B*; the pointed-to object is still a C. Virtual dispatch always looks at the real object's vtable, not the pointer's declared type, so q->f() still calls the most-derived override, C::f, printing C.

More OOP with C++ and Java questions

Exams that ask this topic