C++ Virtual Destructor
Introduction
When we are implementing C++ runtime polymorphism using virtual methods, sometimes we would forget to make the destructor virtual. In this blog post, I would like to discuss the consequence of not using virtual destructor using some examples.
Examples
Non-Virtual Destructor
In the base class, sometimes we would just use the default destructor or implement a destructor that is not virtual.
1 |
|
When we compile the program using GCC, the compiler would throw warning to us.
1 | $ g++ destructor.cpp -o destructor -Wall |
When we execute the program, we got the following messages.
1 | $ ./destructor |
So obviously when we are destroying the derived Apple
object via pointers, the base destructor ~Fruit
was called, but the derived destructor ~Apple
was never called.
Virtual Destructor
However, if we make the destructor of the base class virtual.
1 |
|
When we compile the program, GCC will not throw us warning.
1 | $ g++ virtual_destructor.cpp -o virtual_destructor -Wall |
When we execute the program, we got the following messages.
1 | $ ./virtual_destructor |
The derived Apple
object and the base Fruit
object both have been successfully destroyed. This is because when we call delete ptrFruit
. The destructor method points to ~Apple
instead of ~Fruit
. Therefore, ~Apple
was invoked when we call delete ptrFruit
. Once the execution of ~Apple
is done, because of the nature of the derived destructor, the base destructor ~Fruit
will be called then.
Conclusions
Don’t forget to make the destructor virtual when we are using runtime polymorphisms in C++.
C++ Virtual Destructor