ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
struct A {
    virtual std::string name() const { return "A"; }
};
struct B : A {
    std::string name() const override { return "B(" + A::name() + ")"; }
};
struct C : B {
    std::string name() const override { return "C(" + B::name() + ")"; }
};
int main() {
    A *p = new C();
    cout << p->name();
}
  1. A. C(B(A))
  2. B. A
  3. C. C(A)
  4. D. B(A)

Correct answer: A. C(B(A))

p->name() dispatches virtually to the most-derived override, C::name, which explicitly calls B::name() (a statically bound call), which itself explicitly calls A::name() (returning "A"). Building up the string: B wraps it as B(A), and C wraps that as C(B(A)).

More OOP with C++ and Java questions

Exams that ask this topic