ProgrammingModerateMicrosoft/Amazon SDE MCQ · GATE CS

What is printed?

What is printed?
struct B { virtual char id() const { return 'B'; } };
struct D : B { char id() const override { return 'D'; } };
void byVal(B b)        { cout << b.id(); }
void byRef(const B& b) { cout << b.id(); }
int main() {
    D d;
    byVal(d);
    byRef(d);
    B arr[1] = { d };
    cout << arr[0].id();
}
  1. A. DDD
  2. B. BDB
  3. C. BDD
  4. D. DDB

Correct answer: B. BDB

Passing by value and copying into a B array both slice the object to a plain B, so id() returns 'B'. Only the reference keeps the dynamic type D.

More OOP with C++ and Java questions

Exams that ask this topic