×

C++ Virtual Destructor

In C++, a destructor is a class member function that is used to free up space or remove an object of the class that has gone out of scope. The name of a destructor is the same as the name of a class's function Object () {[native code]} function, but the destructor uses a tilde (~) symbol before its function name.

What do you mean by Virtual Destructor?

When the derivative class instances are destroyed using a base class pointer object, a virtual destroyer is used to free up the memory space allocated by the derived class object or instance. A virtual keyword is used in a base or parent class destructor to guarantee that both the base and derived class destructors are invoked at run time, but the derived class is called first and subsequently the base class to free up the space used by both destructors.

Why do we utilize Virtual Destructors?

When an object in the class is no longer in space or the main () function is about to exit, the program automatically calls the destructor to free the memory used by the class destructor method. Due to the initial binding of the compiler, only the parent class destroyer is executed while a pointer object of the base class that refers to the derived class is removed. This avoids invoking the destructor of the derived class, which causes memory leaks in the application. When the virtual keyword is followed by the destructor tilde (~) symbol inside the base class, it ensures that the destructor of the derived class is invoked first. The destructor of the base class is then called to free the space taken up by both destructors in the inheritance class.

In C++, here's an example of a program that shows destructor without utilizing virtual destructor:

#include<iostream> 
#include<bits/sdtc++.h>
#include<stdlib> 
using namespace std;  
class Virtual  
{                              
    public: /* A public access specifier defines Constructor and Destructor function to call by any object in the class. */  
    Virtual() // Constructor function.   
{  
    cout<< "\n Constructor Virtual class";  
}  
 ~Virtual() // Destructor function   
{  
    cout<< "\n Destructor Virtual class";  
}  
};  
  
class Derived: public Virtual  
{  
    public: /* A public access specifier defines Constructor and Destructor function to call by any object in the class. */  
    Derived() // Constructor function   
{  
    cout << "\n Constructor Derived class" ;  
}  
 ~Derived() // Destructor function   
{  
    cout << "\n Destructor Derived class" ; /* Destructor function is not called to release its space. */  
}         
};  
int main()  
{  
    Virtual *Vptr = new Derived; // Create a Virtual class pointer object   
       delete Vptr; /* Here pointer object is called to delete the space occupied by the destructor.*/  
}  

OUTPUT:

Constructor Virtual class
Constructor Derived class
Destructor Virtual class
……………………………………...
Process exited in 0.7344 seconds with return value 0
Press any key to continue……

Explanation:

When the compiler generates the code, it calls a pointer object in the main method that references to the Virtual class, as seen in the preceding output. As a result, it runs the function Object () {[native code]} () method of the Virtual class before moving on to the function Object () {[native code]} () code of the derived class. The pointer held by the Virtual Class Destroyer and Derived Class Destroyer is then discarded. Virtual class pointers only call. Destroyer of Virtual class not destroyer of derived class. As a result, the program's memory is leaked.

Important: Because the pointer object points to the Virtual class, only the Virtual class destroyer will be called or its occupied space will be removed if the Virtual class destroyer does not use the virtual keyword. Consequently, the derivative class does not call the destroyer to free the memory used by the derivative class, resulting in memory leakage.

In C++, here's an example of a program that shows destructor utilizing virtual destructor:

#include<iostream>
#include<bits/sdtc++.h>
#include<stdlib>  
using namespace std;  
class Virt  
{  
    public:  
    Virt() // Constructor member function.    
{  
    cout << "\n Constructor Virtual class";  // It prints first.  
}  
 virtual ~Virt() // Define the virtual destructor function to call the Destructor Derived function.  
{  
    cout << "\n Destructor Base class";  /  
}  
};  
// Inheritance concept  
class Derived: public Virt  
{  
    public:  
    Derived() // Constructor function.  
{  
    cout << "\n Constructor Derived class" ; /* After print the Constructor Virt, now it will prints. */  
}  
 ~Derived() // Destructor function   
{  
    cout << "\n Destructor Derived class"; /* The virtual Virt Class? Destructor calls it before calling the Virt Class Destructor. */  
}         
};  
int main()  
{  
    Virt *Vptr = new Derived; // A pointer object reference the Virt class.  
    delete Vptr; // Delete the pointer object.  
}  

OUTPUT:

Constructor Virt class
Constructor Derived class
Destructor Derived class
Destructor Virt class
………………………………………..
Process exited in 0.4535 seconds with return value 0
Press any key to exit.

Explanation:

In the program above, we used a virtual destroyer within a base class that calls a derivative class destroyer before calling a base class destroyer to free up space or fix a memory leak.


Related Topics

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

Char Array to String in C++

Regardless of the programming language you use, data structure is critical to the success of your project. Although each programming language has its own collection of data structures, C++ contains a...

4 minutes read.

Free vs delete() in C++

Free vs delete() in C++ In this section, we will learn about the free() function and also create a C ++ program of the delete operator. What is free() Function in C++? In...

4 minutes read.

Structure Sorting (By Multiple Rules) in C++

To understand the concept of Structure Sorting (By Multiple Rules) in C++, it is recommended to know the Structures concept in the C++ programming language. Here the scenario is pretty...

3 minutes read.

Do-While Loop Examples in C++

Before we move on the examples of Do-While loop, let’s learn little bit about the Do-While loop in C++ language. Do While loop An iterative loop that checks the condition at the...

5 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

How to find the length of the vector in C++

Like dynamic arrays, vectors can automatically adjust their size when an element is added or removed, and the container manages its storage. Because vector items are stored in contiguous storage, iterators...

3 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.

Destructor

Let’s discover the C++ destructor, virtual and pure virtual destructors, and when destructors are invoked and their rules in this lesson. Destructors : A member function that destroys an object is known as...

5 minutes read.

Dynamic Memory Allocation in C++

In some programming situations, the number of data items changes as the program is running, which is known as dynamic data or input. Consider a real-world situation where a program...

3 minutes read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

4-Dimensional Array in C/C++

A four-dimensional (4D) array is an array of three-dimensional (3D) arrays, or in other words we can say that a 4- dimensional array is an array of arrays of arrays...

3 minutes read.

C++ Goto

In this article, we will discuss the C++ goto statement with its syntax, use, key features, key points, pseudo code, and examples. What is the goto statement in C++? In C++, the...

4 minutes read.

C++ | C Plus Plus Data type

Data type in every language is very important. Data type means the different kinds of data that are supported by a particular programming language. A computer language’s data types specify the...

15 minutes read.

Vector Size in C++

What are Vectors?  In the C++ programming language, vectors are run-time sequence containers representing arrays with variable sizes, which are contained within STL (Standard Template Library). They utilize contiguous storage spaces...

6 minutes read.

Star pattern in C++ using For Loops

Star patterns are one of the most extensively utilized patterns in any programming language since they help to increase logical thinking and flow control understanding.In the C++ programming language, you...

3 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

Program to arrange an array in alternate positive and negative numbers

Let’s say, there is given an array arr, arrange the array in such a way that every positive number is followed by a negative number. If there are extra positive...

4 minutes read.