![]() |
In C++, destructors are special members of a class that frees memory occupied by an object when it goes out of scope. A virtual destructor is a special form of destructor that is declared as virtual in a base class. In this article, we will discuss the cases when the need for a virtual destructor arises. When to Use Virtual Destructors?Virtual destructors in C++ are needed in scenarios in which polymorphism and inheritance are involved, and instances of derived classes are managed pointers to base classes. If your class has one or more virtual functions that are derived by their child classes and you are using pointers to base class to manage the objects, then you need to implement a virtual destructor so that the relevant version of the destructor is called when the object is deleted. ExampleIn the below code, we won’t use the virtual constructor and see how the objects are destroyed. C++
Output
base constructor derived constructor base destructor Here, only the Base class destructor is called for the Derived class object that is being referred to by the Base class pointer. Due to this, the resources allocated inside the base class are not released leading to memory leaks. In this case, we can make the destructor virtual so that the most derived implementation of it is called. C++ Program to Show the Use of Virtual DestructorC++
Output
base constructor derived constructor derived destructor base destructor If you have the case of multilevel inheritance, the destructor will be called in the order of derivation. |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |