ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
struct Base {
    virtual void f() const { cout << "Base-const"; }
};
struct Derived : Base {
    void f() const override { cout << "Derived-const"; }
};
int main() {
    const Base *p = new Derived();
    p->f();
}
  1. A. Base-const
  2. B. Derived-const
  3. C. Compile-time error: cannot call a const virtual function through a const pointer
  4. D. Undefined behaviour

Correct answer: B. Derived-const

Both Base::f and Derived::f are declared const, so they have matching signatures and Derived::f genuinely overrides Base::f. A const Base* can call const member functions, and virtual dispatch still looks at the real object's vtable, so it prints Derived-const.

More OOP with C++ and Java questions

Exams that ask this topic