ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
struct B {
    virtual void f() = 0;
};
void B::f() { cout << "B"; }
struct D : B {
    void f() override { cout << "D"; B::f(); }
};
int main() {
    D d;
    B& r = d;
    r.f();
    r.B::f();
}
  1. A. DB
  2. B. DBD
  3. C. It does not compile: a pure virtual function cannot have a body
  4. D. DBB

Correct answer: D. DBB

A pure virtual function may still be defined; B stays abstract, but derived classes can call the definition explicitly. r.f() dispatches to D::f, which prints D and then calls B::f (B). r.B::f() is a qualified call, which suppresses virtual dispatch and calls B's definition directly (B).

More OOP with C++ and Java questions

Exams that ask this topic