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();
}- A. A
- B. B
- C. C
- 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
- What is printed? java interface Flyer { default String move() { return "fly"; } } interface Swimmer { default String move() { return…
- What is printed? java class Counter { protected int count = 0; void inc() { count++; } } class LoggingCounter extends Counter { @Override…
- What is printed? cpp struct Base { virtual void f() const { cout << "Base-const"; } }; struct Derived : Base { void f() const override {…
- What is printed? java class Shape { double area() { return 0; } } class Circle extends Shape { double radius; Circle(double r) { radius =…
- What is printed? java class Node { Node next; int val; Node(int v) { val = v; } @Override public String toString() { return "N(" + val +…
- What is printed? java class Employee { double bonus() { return 1000; } double pay() { return 50000 + bonus(); } } class Manager extends…