Search⌘ K
AI Features

Discussion: A Destructive Relationship

Learn how C++ handles the destruction of derived and base class objects through virtual destructors. Understand why destructors call in a specific order, the role of subobjects, and how RAII techniques like unique_ptr help manage resources safely during object destruction.

Run the output

Now, it’s time to execute the code and observe the output.

C++ 17
#include <iostream>
#include <memory>
struct Widget
{
virtual void draw() { std::cout << "Widget draw\n"; }
virtual ~Widget() { std::cout << "Widget destructor\n"; }
};
struct Button : public Widget
{
void draw() override { std::cout << "Button draw\n"; }
~Button() override { std::cout << "Button destructor\n"; }
};
int main()
{
std::unique_ptr<Widget> widget = std::make_unique<Button>();
widget->draw();
}

Understanding the output

When we call draw(), the program only prints Button draw. But when unique_ptr goes out of scope, and the destructor is called, the program prints both Button destructor and Widget destructor. Why is that?

Virtual functions

A common technique for dynamic polymorphism is using virtual functions. We ...