ProgrammingHardMicrosoft/Amazon SDE MCQ · GATE CS

Which statement about this code is correct?

Which statement about this code is correct?
struct B { virtual void f() const { } };
struct D : B { void f() override { } };
  1. A. It compiles, and D::f overrides B::f
  2. B. It compiles, and D::f hides B::f without overriding it
  3. C. It fails to compile, because D::f marked override does not override anything
  4. D. It fails to compile, because a const function cannot be virtual

Correct answer: C. It fails to compile, because D::f marked override does not override anything

D::f is non-const while B::f is const, so the signatures differ and D::f does not override B::f. Without override it would silently hide B::f; with override the compiler must reject it.

More OOP with C++ and Java questions

Exams that ask this topic