ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
struct Base {
    virtual void f() { cout << "B"; }
};
struct Mid : Base {
};
struct Leaf : Mid {
    void f() override { cout << "L"; }
};
int main() {
    Mid *p = new Leaf();
    p->f();
}
  1. A. B
  2. B. L
  3. C. Compile-time error: Mid does not declare f()
  4. D. Compile-time error: Leaf::f does not override anything in Mid

Correct answer: B. L

Leaf::f() overrides Base::f() directly through the inheritance chain (Mid simply passes the virtual function through unchanged). p is declared as Mid* but points at a Leaf object; virtual dispatch finds the most-derived override in the real object's vtable, Leaf::f, printing L.

More OOP with C++ and Java questions

Exams that ask this topic