DESTRUCTORS:
C++ destructor is a special member function that is executed automatically when
an object is destroyed that has been created by the constructor. C++ destructors
are used to de-allocate the memory that has been allocated for the object by the
constructor.
There are two restrictions on the use of destructors:
You cannot take its address.
Derived classes do not inherit the destructor of their base class.
When is destructor called?
A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called
How destructors are different from a normal member function?
Destructors have same name as the class preceded by a tilde (~)
Destructors don’t take any argument and don’t return anything
Destructor rules
1) Name should begin with tilde sign(~) and must match class name.
2) There cannot be more than one destructor in a class.
3) Unlike constructors that can have parameters, destructors do not allow any
parameter.
4) They do not have any return type, just like constructors.
5) When you do not specify any destructor in a class, compiler generates a default
destructor and inserts it into your code.
Destructor in c++ programming
Its syntax is same as constructor except the fact that it is preceded by the tilde sign.
~class_name() { }; //syntax of destructor
Structure of C++ destructors
/*...syntax of destructor....*/
class class_name
{
public:
class_name(); //constructor.
~class_name(); //destructor.
}
Unlike constructor a destructor neither takes any arguments nor does it
returns value. And destructor can’t be overloaded.
C++ Destructor Example
#include <iostream>
class ABC
{
public:
ABC () //constructor defined
{
cout << "Hey look I am in constructor" << endl;
}
~ABC() //destructor defined
{
cout << "Hey look I am in destructor" << endl;
}
};
int main()
{
ABC cc1; //constructor is called
cout << "function main is terminating...." << endl;
return 0;
}
Output
Hey look I am in constructor
function main is terminating....
Hey look I am in destructor
Program based on destructor.
#include<iostream>
using namespace std;
class Demo {
private:
int num1, num2;
public:
Demo(int n1, int n2) {
cout<<"Inside Constructor"<<endl;
num1 = n1;
num2 = n2;
}
void display() {
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
~Demo() {
cout<<"Inside Destructor";
}
};
int main() {
Demo obj1(10, 20);
obj1.display();
return 0;
}
Output
Inside Constructor
num1 = 10
num2 = 20
Inside Destructor
Program :
1. #include <iostream>
2. class Employee
3. {
4. public:
5. Employee()
6. {
7. cout<<"Constructor Invoked"<<endl;
8. }
9. ~Employee()
10. {
11. cout<<"Destructor Invoked"<<endl;
12. }
13.};
14.int main(void)
15.{
16. Employee e1; //creating an object of Employee
17. Employee e2; //creating an object of Employee
18. return 0;
19.}
Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked