Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
In this tutorial, you learn about Destructor in C++ programming language. As we know, C++ is an Object-Oriented programming language. It is generally used in IT trades to evolve software, embedded firmware, drivers, and client-server applications. C++ is a middle-level programming language that has to encapsulate an aspect of both high-level and low-level programming languages. It has an idea of classes and objects. In C++, the constructors perform a vital role in building an object and initializing the instance variables. But what happens to certain objects and resources after they are no longer in use or the program ends? This ability is performed by Destructors in C++.
Destructors are used to crush the objects created by the Constructors when they are no longer required to clear the memory. They are specific member functions and are called automatically by C++. Compiler to free up some memory when there is no user-defined destructor in the program. Constructors and destructors also have the same name as the class introduced by a tilde (~) sign. But the destructor doesn’t take any arguments/parameters and does not return anything, e.g they don’t have any return type.
Destructors can never be overloaded like constructors in a class. In the following section, we provided are some of the conditions where the destructor is called automatically by the compiler:
A programmer can specify a destructor known as a user-designed constructor. A destructor can hold as Virtual but can not be declared volatile, const volatile, or static.
Syntax:
The Destructors in the C++ programming language are started by the tilde(~) sign. The syntax of declaring destructor is…
~name() { Destructor Body; // statement of desctructor goes here. }
Example:
#include <iostream> using namespace std; class Name { public: Name () // Defined Constructor { cout << "Hey look I am in constructor" << endl; } ~Name() //Here we defined a destructor. { cout << "Hey look I am in destructor" << endl; } }; int main() { Name cc1; // Here we called a constructor. cout << "function main is terminating...." << endl; /*....object cc1 goes out of scope ,now destructor is being called...*/ return 0; }
The above information on destructors explains the use and implementation of destructors in C++ programs. However, The concept of the destructor is not difficult yet it is very essential to understand before implementation in the program as incorrect use of the destructor can lead to some unexpected results. Above all, keep in mind for further.