ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
struct Base {
    virtual void render() const { cout << "Base::render "; }
};
struct Derived : Base {
    void render() const override { cout << "Derived::render "; }
};
void draw(const Base *items[], int n) {
    for (int i = 0; i < n; i++) items[i]->render();
}
int main() {
    const Base *arr[2] = { new Base(), new Derived() };
    draw(arr, 2);
}
  1. A. Base::render Base::render
  2. B. Base::render Derived::render
  3. C. Derived::render Derived::render
  4. D. Compile-time error: const Base* cannot call a virtual function

Correct answer: B. Base::render Derived::render

Each pointer in arr keeps the type of the object it was allocated as; const simply forbids modifying the pointed-to object, not calling const-qualified or non-mutating virtual functions. Dispatch is based on each element's real object: Base prints Base::render, Derived prints Derived::render.

More OOP with C++ and Java questions

Exams that ask this topic