ProgrammingHardAccenture · Cognizant pattern

What is printed?

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

Correct answer: A. Derived-f

f() is virtual, so p->f() dispatches to Derived::f() at runtime, which only prints "Derived-f " and, since Derived::f overrides the whole body (it does not call Base::f), g() is never invoked at all.

More OOP with C++ and Java questions

Exams that ask this topic