ProgrammingVery hardProduct company OA

What is printed?

What is printed?
struct Base {
    virtual void f() const { std::cout << "Base::f const"; }
};
struct Derived : Base {
    void f() { std::cout << "Derived::f non-const"; } // note: no const here
};
int main() {
    Base *p = new Derived();
    p->f();
}
  1. A. Derived::f non-const
  2. B. Compilation error: Derived::f does not override anything meaningfully, it's a separate non-virtual overload that hides Base::f
  3. C. Both print
  4. D. Base::f const

Correct answer: D. Base::f const

Derived::f() lacks the const qualifier, so its signature (void f()) differs from Base::f() const — it does NOT override the virtual function; it is an unrelated new (non-virtual) member that merely hides Base::f by name. Through a Base* pointer, only Base's virtual f() const is considered, and since it's virtual but Derived never actually overrode it, the vtable still points at Base::f(), printing "Base::f const".

More OOP with C++ and Java questions

Exams that ask this topic