Virtual Destructor

on

Destructor in the base class can be declared virtual. If up casting is done, destructor of the base class must be virtual for proper destruction of the object else it may result in memory leak. As the object of derived class remains un-destruct.

#include<iostream>
using namespace std;

class Base{
public:
    ~Base()
    {
        cout<<"Base";
    }
};
class Derived : public Base
{
public:
    ~Derived()
    {
        cout<<"Derived";
    }
};

int main()
{
    Base *b = new Derived();
    delete b;
}

Output:
Base

Upcasting with Virtual Destructor

class Base{
public:
    virtual ~Base()
    {
        cout<<"Base";
    }
};

Output:
DerivedBase

Pure Virtual Destructor

Pure Virtual destructor is legal in C++. Also it must be defined/ it is must to provide function body, which is against the pure virtual behavior.

#include<iostream>
using namespace std;

class Base{
public:
    virtual ~Base() = 0;
};
class Derived : public Base
{
public:
    ~Derived()
    {
        cout<<"Derived";
    }
};
Base :: ~Base()
{
        cout<<"Base";
}
int main()
{
    Base *b = new Derived();
    delete b;
}

Output:
DerivedBase

Note: A Constructor of a class cannot be Virtual.

Advertisements

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s