Sunday, May 18, 2008
What is a virtual destructor?
  • Virtual destructor ensures that the object destruction happens from the most derived class towards the base class.
  • Significant in scenarios where a derived class object is assigned to a base class pointer.
EXAMPLE: Demonstrate the object destruction sequence.
#include <iostream>

using namespace std;

class Base {

    public:
        Base() {
            cout << "Base class constructor ..." << endl;
        }
        ~Base() {
            cout << "Base class destructor ..." << endl;
        }
};

class Derived : public Base {

    public:
        Derived() {
            cout << "Derived class constructor ..." << endl;
        }
        ~Derived() {
            cout << "Derived class destructor ..." << endl;
        }
};

void main()
{
    Base* base;
    base = new Derived();
    delete base;
}

OUTPUT:
Base class constructor ...
Derived class constructor ...
Base class destructor ...


EXAMPLE: Demonstrate the object destruction sequence using virtual destructor

#include <iostream>

using namespace std;

class Base {

    public:
        Base() {
            cout << "Base class constructor ..." << endl;
        }
        virtual ~Base() {
            cout << "Base class destructor ..." << endl;
        }
};

class Derived : public Base {

    public:
        Derived() {
            cout << "Derived class constructor ..." << endl;
        }
        ~Derived() {
            cout << "Derived class destructor ..." << endl;
        }
};

void main()
{
    Base* base;
    base = new Derived();
    delete base;
}
OUTPUT:
Base class constructor ...
Derived class constructor ...
Derived class destructor ...
Base class destructor ...

Contact Form

Name

Email *

Message *

Back to Top