ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
struct Base {
    virtual void save() { cout << "BaseSave "; }
};
struct Derived : Base {
    void save() override { cout << "DerivedSave "; Base::save(); }
};
int main() {
    std::unique_ptr<Base> p = std::make_unique<Derived>();
    p->save();
}
  1. A. DerivedSave
  2. B. BaseSave
  3. C. DerivedSave BaseSave
  4. D. Compile-time error: cannot explicitly call Base::save() from an override

Correct answer: C. DerivedSave BaseSave

p->save() dispatches virtually to Derived::save (since the managed object is a Derived), printing DerivedSave; inside it, the explicit, statically-bound call Base::save() runs Base's own implementation too, printing BaseSave. Output: DerivedSave BaseSave.

More OOP with C++ and Java questions

Exams that ask this topic