ProgrammingHardAccenture · Cognizant pattern

What is printed?

What is printed?
struct Base {
    void who() { cout << "Base"; }
};
struct Derived : Base {
    void who() { cout << "Derived"; }
};
int main() {
    Base *p = new Derived;
    p->who();
}
  1. A. Derived
  2. B. Base
  3. C. Compilation error: who() redefined
  4. D. BaseDerived

Correct answer: B. Base

who() is not declared virtual, so the call is resolved statically using the pointer's compile-time type Base*, calling Base::who() regardless of the actual object being a Derived.

More OOP with C++ and Java questions

Exams that ask this topic