Virtual Destructors
Completed
Write class Base with a virtual destructor printing ~Base, and Derived whose destructor prints ~Derived NAME. For each name, create a Derived through a unique_ptr<Base>, print made NAME, then reset it.
Input
n, then n names.
Output
The event trace.
Example
Input
2 A B
Output
made A ~Derived A ~Base made B ~Derived B ~Base
Editor
C++
Hints
Without virtual, deleting through a Base pointer would skip ~Derived.
Solution explanation
Destructors run from the most derived class up to the base.
Show solution
#include <iostream>
#include <memory>
#include <string>
using namespace std;
class Base {
public:
virtual ~Base() { cout << "~Base\n"; }
};
class Derived : public Base {
public:
explicit Derived(string name) : name_(name) {}
~Derived() override { cout << "~Derived " << name_ << "\n"; }
private:
string name_;
};
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string name;
cin >> name;
unique_ptr<Base> p = make_unique<Derived>(name);
cout << "made " << name << "\n";
p.reset();
}
return 0;
}