Question 16
Back to Exercise
What is the output of the following C++ program?
#include <iostream>
#include <memory>
struct Base {
Base() { std::cout << "B "; }
virtual ~Base() { std::cout << "~B "; }
};
struct Mid : Base {
Mid() { std::cout << "M "; }
~Mid() override { std::cout << "~M "; }
};
struct Leaf : Mid {
Leaf() { std::cout << "L "; }
~Leaf() override { std::cout << "~L "; }
};
int main() {
std::unique_ptr<Base> p = std::make_unique<Leaf>();
std::cout << "| ";
p.reset();
std::cout << '\n';
return 0;
}
- A B M L | ~L ~M ~B Correct
- B B M L | ~B
- C L M B | ~B ~M ~L
- D B M L | ~B ~M ~L
Correct Answer: Option A
Construction goes from the base down; because ~Base is virtual, deleting through the Base pointer starts at ~Leaf and runs every destructor in reverse.
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!