top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is a pure virtual destructor in C++?

0 votes
524 views

What is a pure virtual destructor in C++? What is its need, advantage and disadvantage, please explain with example?

posted Jan 17, 2015 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

In C++ a destructor is generally used to deallocate memory and do some other cleanup for a class object and it’s class members whenever an object is destroyed. Destructors are distinguished by the tilde, the ‘~’ that appears in front of the destructor name. In order to define a virtual destructor, all you have to do is simply add the keyword “virtual” before the tilde symbol.

Destructors are always called in the reverse order of the class derivation. That means derived class destructor will be invoked first & then base class destructor will be called. If definition for the pure virtual destructor is not provided then what function body will be called during object destruction? Therefore compiler & linker enforce existence of function body for pure virtual destructor.
Consider following program:

#include <iostream>
class Base
{
public:
    virtual ~Base()=0; // Pure virtual destructor
};

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

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

The linker will produce following error in the above program.

test.cpp:(.text$_ZN7DerivedD1Ev[__ZN7DerivedD1Ev]+0x4c):
undefined reference to `Base::~Base()'
Now if the definition for the pure virtual destructor is provided then the program compiles & runs fine.

#include <iostream>
class Base
{
public:
    virtual ~Base()=0; // Pure virtual destructor
};
Base::~Base()
{
    std::cout << "Pure virtual destructor is called";
}

class Derived : public Base
{
public:
    ~Derived()
    {
        std::cout << "~Derived() is executed\n";
    }
};

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

Output:

~Derived() is executed
Pure virtual destructor is called
answer Jan 18, 2015 by Amit Kumar Pandey
...