Destructors

Destructors
Destructors
CONCEPT

A destructor is a member function that is automatically called when an object is destroyed.

EXPLANATION

Destructors are public member functions with the same name as the class, preceded by a tilde character (~). For example, the destructor for the Rectangle class would be named ~Rectangle.
Destructors are automatically called when an object is destroyed. In the same way that constructors can be used to set things up when an object is created, destructors are used to perform shutdown procedures when the object goes out of existence.
1 // This program demonstrates a destructor.
2 #include <iostream>
3 using namespace std;
4
5 class Demo
6 {
7 public:
8 Demo(); // Constructor prototype
9 ~Demo(); // Destructor prototype
10 };
11
12 Demo::Demo() // Constructor function definition
13 { cout << "An object has just been defined, so the constructor"
14 << " is running.\n";
15 }
16
17 Demo::~Demo() // Destructor function definition
18 { cout << "Now the destructor is running.\n";
19 }
20
21 int main()
22 {
23 Demo demoObj; // Declare a Demo object;
24
25 cout << "The object now exists, but is about to be destroyed.\n";
26 return 0;
27 }
Program Output
An object has just been defined, so the constructor is running.
The object now exists, but is about to be destroyed.
Now the destructor is running.

MORE ON DESTRUCTOR


In addition to the fact that destructors are automatically called when an object is destroyed, the following points should be mentioned:
• Like constructors, destructors have no return type.
• Destructors cannot accept arguments, so they never have a parameter list.
• Because destructors can accept no arguments, there can only be one destructor.
Previous
Next Post »