Question 6
Back to Exercise
What is the output of the following C++ program on a 64-bit system?
#include <iostream>
#include <memory>
#include <vector>
struct Animal {
virtual const char* sound() const = 0;
virtual ~Animal() { std::cout << "~Animal "; }
};
struct Dog : Animal {
const char* sound() const override { return "Woof"; }
~Dog() override { std::cout << "~Dog "; }
};
int main() {
{
std::vector<std::unique_ptr<Animal>> zoo;
zoo.push_back(std::make_unique<Dog>());
std::cout << zoo[0]->sound() << ' ';
}
std::cout << '\n';
return 0;
}
- A Woof ~Dog ~Animal Correct
- B Woof ~Animal
- C Woof ~Animal ~Dog
- D Woof
Correct Answer: Option A
When the vector is destroyed, each unique_ptr deletes through Animal*; the virtual destructor makes ~Dog run first.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!