Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Virtual destruction using shared_ptr in C++
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
#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
Advertisements
