Virtual Destruction using shared_ptr in C++

In this tutorial, we will discuss the virtual destructor using shared_ptr in C++. Also, we will implement a C++ program that will demonstrate the working of shared_ptr.

What is shared_ptr?

Virtual destructor is to destruct the resources and memory allocations in a proper order, for example; when you delete a base class pointer pointing to derived class object.

Shared pointer has some of the in-built features such as automatic or default memory management techniques which help retain the used memory from the heap environment. The prominent intention of using shared pointers is that there can be multiple such pointers that points or refers to the same resource. And its base feature is that even if the programmer deletes the pointer referencing the resource, the resource isn’t de-referenced until and unless the last remaining pointer isn’t terminated or de-referenced.

Following is the demonstration of shared_ptr as virtual destructor():

#include <iostream>
#include <memory>
using namespace std;
class base_class {
   public:
   base_class()
   {
      cout << "Constructing base class" << endl;
   }
   ~base_class(){
      cout << "Destructing base class" << endl;
   }
};

class derived_class : public base_class {
   public:
   derived_class()
   {
      cout << "Constructing derived_class" << endl;
   }
   ~derived_class(){
      cout << "Destructing derived_class" << endl;
   }
};
int main()
{
   std::shared_ptr<base_class> sp{ new derived_class };
   return 0;
}
Output:

Constructing base class
Constructing derived_class
Destructing derived_class
Destructing base class

Explanation: In the above program I have declared the base_class and the derived_class with their own constructor and destructor. In the main function, the object ‘sp’ of the shared_ptr is created which refers to the derived_class. But the shared pointer initializes the base class and then the derived class. The output represents the working of the program.

 

Leave a Reply

Your email address will not be published. Required fields are marked *