ProgrammingHardMicrosoft/Google SDE MCQ · GATE CS

What is printed?

What is printed?
struct B {
    virtual void f() { cout << "B"; }
    void g() { f(); }
};
struct D : B {
    void f() override { cout << "D"; }
};
int main() {
    D d;
    B b = d;
    b.g();
    d.g();
    B* p = &d;
    p->B::f();
}
  1. A. DDB
  2. B. BDB
  3. C. BDD
  4. D. DDD

Correct answer: B. BDB

B b = d slices, so b is a real B and g() calls B::f (B). d.g() calls f() through this, which dispatches to D::f (D). A qualified call p->B::f() suppresses virtual dispatch (B).

More OOP with C++ and Java questions

Exams that ask this topic