Virtual destruction using shared_ptr in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to understand virtual destruction using shared_ptr in C++.

To delete the instances of a class, we define the destructor of the base class to be virtual. So it deletes the various object instances inherited in the reverse order in which they were created.


 Live Demo

#include <iostream>
#include <memory>
using namespace std;
class Base {
      cout << "Constructing Base" << endl;
      cout << "Destructing Base" << endl;
class Derived : public Base {
      cout << "Constructing Derived" << endl;
      cout << "Destructing Derived" << endl;
int main(){
   std::shared_ptr<Base> sp{ new Derived };
   return 0;


Constructing Base
Constructing Derived
Destructing Derived
Destructing Base
Published on 12-Mar-2020 06:35:57