Virtual constructors and destructors

A constructor in c++ can never be virtual.

But a destructor can be. 

It is always advisable to use virtual destructors. 

Say we have a pointer to base class, pointing to derived class object and if we call delete on this object, the program will only call destructor of the base class.   

class base {....};
class derived:public base{...};
int main()
{
    base *ptr = new derived();
    .......
    delete ptr;
.....

Now delete ptr in the code above deletes the object, but it calls base destructor, but not derived destructor. Hence resources allocated in derived will not be released. And this will cause memory leakage.

Hence if your class has any virtual functions, then make destructor of your class virtual.

If base class destructor is virtual, calling delete will use dynamic binding to go to dericed class and calling its destructor. And as always, once derived destructor is called, this will call base class destructor. 

Comments

Popular Posts