ProgrammingHardInfosys · GATE CS

What is printed? (C++, assume <iostream> and using namespace std)

What is printed? (C++, assume <iostream> and using namespace std)
struct B {
    B() { f(); }
    virtual void f() { cout << "B"; }
};
struct D : B { void f() override { cout << "D"; } };
int main() { D d; }
  1. A. D
  2. B. B
  3. C. BD
  4. D. DB

Correct answer: B. B

While B's constructor runs, the object is only a B, so the virtual call resolves to B::f.

More OOP with C++ and Java questions

Exams that ask this topic