ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
struct Base {
    virtual void run() { step1(); step2(); }
    virtual void step1() { cout << "B1 "; }
    virtual void step2() { cout << "B2 "; }
};
struct Derived : Base {
    void step1() override { cout << "D1 "; }
};
int main() {
    Base *p = new Derived();
    p->run();
}
  1. A. B1 B2
  2. B. D1 B2
  3. C. D1 D1
  4. D. B1 D1

Correct answer: B. D1 B2

This is the template-method pattern: run() is inherited unchanged from Base, but its internal calls to step1() and step2() are both virtual. step1() dispatches to Derived's override (D1); step2() is not overridden by Derived, so it falls back to Base's own version (B2). Result: D1 B2.

More OOP with C++ and Java questions

Exams that ask this topic