ProgrammingHardMicrosoft/Google SDE MCQ · GATE CS

What is printed?

What is printed?
struct A { virtual void f() = 0; };
void A::f() { cout << "A"; }
struct B : A { void f() override { A::f(); cout << "B"; } };
int main() {
    B b;
    A& r = b;
    r.f();
}
  1. A. B
  2. B. Compile error: a pure virtual function cannot have a body
  3. C. AB
  4. D. BA

Correct answer: C. AB

A pure virtual function may still be defined; it keeps A abstract, but a derived class can call it explicitly with A::f(). r.f() dispatches to B::f, which prints A and then B.

More OOP with C++ and Java questions

Exams that ask this topic