Search This Blog

Thursday, September 20, 2012

Virtual destructor

One of the common C++ interview question is what is virtual destructor? Or what is the use of virtual destructor?
You are assigning a derived class object to a base class pointer and deleting the base class pointer.
If the base class destructor is not declared as virtual, then derived class destructor won’t get called.
If you are deleting some variables allocated heap memory in derived class destructor, then it will cause memory leak.



// CPPSamples.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
class Base
{
    public:
    Base()
    {
        cout<<"\n Base class Constructor\r\n";
    }
    ~Base()
    {
        cout<<"\n Base class Destructor\r\n";
    }

};
class Derived:Base
{
public:
    Derived()
    {
        cout<<"\n Derived class Constructor\r\n";
    }
    ~Derived()
    {
        cout<<"\n Derived class Destructor\r\n";
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Base *ptr=(Base*)new Derived();
    delete ptr;
    getch();
    return 0;
}
 

 


 
If the base class Destructor is virtual then,
 
// CPPSamples.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
class Base
{
    public:
    Base()
    {
        cout<<"\n Base class Constructor\r\n";
    }
    virtual ~Base()
    {
        cout<<"\n Base class Destructor\r\n";
    }

};
class Derived:Base
{
public:
    Derived()
    {
        cout<<"\n Derived class Constructor\r\n";
    }
    ~Derived()
    {
        cout<<"\n Derived class Destructor\r\n";
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Base *ptr=(Base*)new Derived();
    delete ptr;
    getch();
    return 0;
}
 
 

No comments:

Post a Comment