In C++, a destructor is a special member function of a class that is automatically called when an object of that class goes out of scope or is explicitly destroyed. It is used to clean up any resources or perform any necessary actions before the object is destroyed.
The syntax for a destructor in C++ is similar to that of a constructor but with a tilde (~) followed by the class name.
Here’s an example:
class MyClass {
public:
// Constructor
MyClass() {
// Initialization code
}
// Destructor
~MyClass() {
// Cleanup code
}
// Other member functions and data members
};
The destructor does not have any parameters, and you can only have one destructor per class. The name of the destructor is always the same as the class name, preceded by a tilde.
The destructor(tilde operator(~)) is automatically called when an object is destroyed. This can happen when the object goes out of scope, such as when a local object is created inside a function and the function ends.
Here’s an example :
#include <iostream>
class MyClass {
public:
MyClass() {
std::cout << “Constructor called” << std::endl;
}
~MyClass() {
std::cout << “Destructor called” << std::endl;
}
};
int main() {
MyClass obj; // Create an object of MyClass
// Other code…
return 0; // Object obj goes out of scope and the destructor is called
}
In the above example, when the object obj
goes out of scope at the end of the main
function, the destructor MyClass
is automatically called. The destructor prints a message indicating that it has been called.
Example with output
#include<iostream.h>
#include<conio.h>
class abc
{
public:
abc()
{
cout<<“constructor”;
}
~abc()
{
cout<<“destructor”;
}};
main()
{
clrscr();
abc ob1;
getch();
}