ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
struct Base {
    virtual int value() const { return 10; }
};
struct Derived : Base {
    int value() const override { return Base::value() + 5; }
};
struct MostDerived : Derived {
    int value() const override { return Derived::value() * 2; }
};
int main() {
    Base *p = new MostDerived();
    cout << p->value();
}
  1. A. 10
  2. B. 15
  3. C. 30
  4. D. 20

Correct answer: C. 30

MostDerived::value() explicitly calls Derived::value() (a static, non-virtual-dispatch call by qualified name), which itself explicitly calls Base::value() (returning 10), adds 5 to get 15, and MostDerived then doubles that to 30. The virtual call via p->value() dispatches to MostDerived's override, which drives this whole chain, printing 30.

More OOP with C++ and Java questions

Exams that ask this topic