Sunday, April 13, 2008

C++ : The need for virtual destructors

With the advent of object oriented languages the use of polymophism became very common .
In C++ when you have a derived Class and a base class .

when you have code like this :

class Base {
};

class Derived : public Base{
};

Base * p = new Derived();

delete p;

what's wrong with it .

Since this piece of code is based on polymorphism , the base pointer will refer to an instance of a derived class object .

when delete on the pointer p is called , due to static typing in c++ , destructor of Base is called , instead of Derived . To correct this

virtual ~Base(){
}

should be added . By making the destructor virtual the destructor of the derived class would be called now .

No comments: