I'ts been a long time ago when I posted a [TIP] for the last time. A [TIP] is a mini-tutorial that takes 5 tot 10 minutes to study.
The Virtual Destructor
Imagine code like:
Code:
BaseClass* Bc = new DerivedClass;
delete Bc;
DerivedClass is a class derived from BaseClass
Question: is DerivedClass destructor called?
Answer: to make sure it does, make the destructor of the base class
virtual.
That's all there's to it.
Example code:
Code:
#include <iostream>
using namespace std;
class Base
{
public:
/* virtual*/ ~Base()
{
cout<<"Base Dtor called"<<endl;
}
};
class Derived : public Base
{
public:
~Derived()
{
cout<<"Derived Dtor called"<<endl;
}
};
int main()
{
Base* Bp = new Derived;
delete Bp;
return 0;
}
Compile it, run it.
See the output?
Only the base class destructor is called.
See the
main() function? The base class pointer points to a derived class! Now you know
when the virtual destructor is becoming relevant.
Now remove the comment-tags from
virtual in the base class.
Compile and run it.
See the output?
Now both the destructor of the base class
and the derived class are called. That's the way to go.
And that's all folks. This topic isn't close to complete, but it's a clear intro I think.