ProgrammingHardProduct-company placement · C++

What is printed?

What is printed?
struct B { virtual string who() const { return "B"; } };
struct D : B { string who() const override { return "D"; } };
int main() {
    vector<B> v;  v.push_back(D());
    D d;
    vector<B*> w; w.push_back(&d);
    vector<unique_ptr<B>> u; u.push_back(make_unique<D>());
    cout << v[0].who() << w[0]->who() << u[0]->who();
}
  1. A. BDD
  2. B. DDD
  3. C. BBD
  4. D. BDB

Correct answer: A. BDD

A vector<B> stores B objects, so pushing a D copies only its B part (slicing) and loses the override. Containers of pointers or smart pointers keep the real D objects and dispatch dynamically.

More OOP with C++ and Java questions

Exams that ask this topic