ProgrammingHardProduct-company MCQ pattern
What happens when this is compiled?
What happens when this is compiled?
struct A {
virtual void f() final { cout << "A"; }
};
struct B : A {
void f() override { cout << "B"; }
};- A. Compiles fine; B::f overrides A::f normally
- B. Compile-time error: f() in A is final and cannot be overridden in B
- C. Compiles, but B::f is silently ignored at runtime
- D. Compile-time error: final cannot be combined with virtual
Correct answer: B. Compile-time error: f() in A is final and cannot be overridden in B
The final specifier on a virtual function in C++11 onward forbids any derived class from overriding it. B's attempt to override f() is rejected at compile time.
More OOP with C++ and Java questions
- What happens when this is compiled? java class A { int m() { return 1; } double m() { return 1.0; } }
- What is printed? cpp void f(int p) { cout << "nonconst "; } void f(const int p) { cout << "const "; } int main() { int x = 5; int p = &x…
- Does this compile? java class Outer { private int x = 5; class Inner { void show() { System.out.println(x); } } }
- What is printed? cpp struct Base { virtual void f() { cout << "Base"; } }; struct Derived : Base { void f() { cout << "Derived"; } }; int…
- What is printed? java class Picker { static void f(int a, int b) { System.out.print("fixed"); } static void f(int... a) {…
- What happens when this is compiled? cpp struct Base final { virtual void f() { cout << "Base"; } }; struct Derived : Base { };