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();
}- A. BDD
- B. DDD
- C. BBD
- 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
- What is printed? cpp struct G { G() { cout << "G"; } ~G() { cout << "g"; } }; G g1; int main() { cout << "M"; static G s; cout << "m"; }
- Which lines fail to compile? cpp struct P { P(int) { } }; int main() { P a[3]; // L1 P b[2] = {1, 2}; // L2 vector<P> v(3); // L3…
- Which line fails to compile? cpp struct B { virtual B clone() { return new B; } virtual int id() { return 1; } }; struct D : B { D clone()…
- What is printed when compiled as C++17? cpp struct A { A() { cout << "D"; } A(const A&) { cout << "C"; } }; int main() { A a = A(A()); }
- What is printed? cpp struct B { B& operator=(int) { cout << "B"; return this; } }; struct D : B { }; int main() { D d; d = 5; }
- What is printed? cpp template <typename T> struct Box { static int count; Box() { count++; } }; template <typename T> int Box<T>::count =…