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.

Example

 Live Demo

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

Output

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