×

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

C++ String Class and its Applications

The String class is available in C++. The character array is represented by the C string. The string class in C++ has a few different attributes. It contains several functions...

4 minutes read.

Web Development in C++

Before learning above C++ web development, we need to learn about CGI What is CGI? CGI stands for common gateway interface. CGI is a standard that tells us how the exchange of...

4 minutes read.

Octal to Decimal in C++

We need to write a system that converts octal number into equal decimal number when octal number is given as input. Let us look at an example of a program in...

2 minutes read.

Virtual class in C++

Introduction to Virtual Base class Virtual base classes can be utilized in virtual inheritance as a mechanism for examining many "instances" of a certain class while searching through multiple inheritances in...

6 minutes read.

Roadmap to C++ Programming

Introduction There are so many programming languages available in the market, but among them, C++ is something that never lost its charm. It has a powerful impact on the programming world....

4 minutes read.

Top 5 IDEs for C++ That You Should Try Once

In the past decades, creating an application or interface from the very basic idea, the developer has to struggle a lot for it. Because an application is a combination of...

3 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

Reverse function in C++

The function std::reverse() is included in the standard template library of C++. It takes in a beginning and ending iterator, reversing the order. To use the reverse statement, we need...

2 minutes read.

Hello World Program in C++

The steps for “Hello World” C++ program are as follows: Write a C++ code given below in an editor. Save the file with .cpp Compile the code using C++ compiler or using online...

3 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.

Scope Resolution Operator vs this Pointer in C++

In this tutorial, we will compare the Scope Resolution operation to this Pointer in C++ language. Scope Resolution Operator The Scope Resolution Operator in C++ programming language is usually denoted by (::)....

3 minutes read.

C++ Structs

We frequently encounter scenarios in which we must store a bunch of data, whether of comparable or dissimilar data kinds. Arrays are used to hold a group of data of...

6 minutes read.

C++ Prime number program

In this lesson, you'll learn how to verify whether a given number is a prime number or not in C++, and you'll obtain code to do it. What is the definition...

3 minutes read.

How to create a stack in C++

A stack is a data structure, which is of linear type. A specific order has to be followed while inserting and deleting the elements from the stack. Generally, stack follows...

5 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

4 Pillars of OOPs

OOPs OOPS means Object Oriented Programming System Structure. Object oriented Programming is defined as an approach that provides a way of modularizing programs by creating partitioned memory area for both data...

11 minutes read.

Pointers in C++

Pointers are a powerful feature in the C++ programming language, allowing developers to directly manipulate memory addresses and create more efficient and dynamic programs. However, pointers can also source various...

3 minutes read.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

How to enter a name in C++

A name is a string or array of characters or letters. The string is one of the most helpful data types offered by the C++ library. A string helps the...

4 minutes read.

Palindrome using For loop in C++

A palindrome is a word, number, phrase, or other sequence of letters that reads the same backward as forward, such as 101 or MOM. Like other programming languages, C++ also allows...

6 minutes read.