Why does a destructor in base class need to be declared virtual?

Let’s think about why we have virtual methods to start with. Suppose we have the following code:

C++:
01 class Foo{
02   public:
03    void f();
04 };
05 
06 class Bar: public Foo{
07   public:
08     void f();
09 }
10 
11 Foo* p=new Bar();
12 p->f();
Calling p->f() will result in a call to Foo::f(). This is because p is a pointer to Foo, and f() is not virtual.
To ensure that p->f() will invoke the most derived implementation of f(), we need to declare f() to be a virtual function.
Now, let’s go back to our destructor. Destructors are used to clean up memory and resources. If Foo’s destructor were not virtual, then Foo’s destructor would be called, even when p is really of type Bar.
This is why we declare destructors to be virtual; we want to ensure that the destructor for the most derived class is called.
Advertisements
This entry was posted in C++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s