Last active
December 28, 2016 15:24
-
-
Save ashwin/f0868a27e9a1f91ab713e3d977f871cd to your computer and use it in GitHub Desktop.
Example showing why C++ base class destructor should be virtual
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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