LearnFrenzy
Sign in Take a free test

Smart Pointers · Predict the Output · Question 6

unique_ptr<Base> owning derived objects Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links