This time I plan to explain to you a C++ brain teaser I came across. With no further adieu, let me get directly to the question:
What is the problem with this code, if any?
(Assurance from me: this code will compile and execute fine. ie. no compilation error)
Hope you have put enough thought on it. Some might have already cracked it. For the rest of the folks, let me reveal it.
Yes, this code has some serious problem at run-time. If not compilation-error, what is it?
You are right; the worst nightmare, memory leak! But where is it leaking?
Let pause that question for a few minutes to discuss something in C++ language.
In a scenario where a Child class inherits a Parent class, when a Child object is created, first the Parent-Constructor is invoked and then the Child-Constructor and when the Child object is destroyed, first the Child-Destructor is invoked and then the Parent-Destructor is executed.
In our above program, we use a variable of type “Parent” to point to a “Child” object. Lets use below program to check if the order of invocation of constructor and destructor is followed in this case.
Output of the above program is:
As you can see, here the child destructor is not invoked, which means, whatever we coded in the Destructor method of Child class is not executed. In our main program, we allocate an array of memory in the Constructor of Child and delete the same in its Destructor. So our main program successfully allocates an array of memory but don’t delete it, which will result in Memory Leak.
So we have answered our question. Now lets see how we can avoid it.
Here is where Virtual-Destructor comes for help. Make the destructor of “Parent” class virtual and this issue is solved.
New implementation of “Parent”:
To put it straight, virtual destructor forces the parent class to check for child class destructors and executes it.
Use a virtual destructor if you ever expect a derived class to be destroyed through a pointer to the base class to ensure that the destructor of the most derived classes gets called.
It’s a good practice to make the destructors of all interface classes, ie. any class with at-least one virtual method, as virtual.