Sunday, May 18, 2008

C++ Virtual Destructor

2 comments

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 ...
If You Enjoyed This, Take 5 Seconds To Share It

2 comments:

  1. Why would some body possibly want to assign Derived class to Base pointer and live with Object Scliceing.

    ReplyDelete
  2. Object Scliceing only happens when the objects are created on stack but not on objects created on heap

    ReplyDelete