Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example showing why C++ base class destructor should be virtual
// Example to show why base class destructor should be virtual.
//
// If ~A is not virtual below, you will notice that B's destructor
// is not called and B's Foo object is not freed. Memory leak!
//
// Change ~A to virtual and Foo is freed at end of scope correctly.
#include <iostream>
#include <memory>
using namespace std;
class Foo
{
public:
Foo() { cout << "Foo ctor\n"; }
~Foo() { cout << "Foo dtor\n"; }
};
// Base class
class A
{
public:
A() { cout << "A ctor\n"; }
// Note: Make this virtual to prevent memory leak
~A() { cout << "A dtor\n"; }
};
// Derived class
class B : public A
{
public:
B()
{
cout << "B ctor\n";
fp = unique_ptr<Foo>(new Foo);
}
~B() { cout << "B dtor\n"; }
unique_ptr<Foo> fp;
};
int main()
{
{
// Take a base class pointer to derived class object
unique_ptr<A> a(new B);
}
cout << "Scope ended\n";
return 0;
}
// If ~A is not virtual, output is:
// A ctor
// B ctor
// Foo ctor
// A dtor
// Scope ended
// If ~A is virtual, output is:
// A ctor
// B ctor
// Foo ctor
// B dtor <-- B destructor called
// Foo dtor <-- Foo object destroyed
// A dtor
// Scope ended
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.