2. I. Destructors:
๏A destructor is a special member function that works just opposite to
constructor.
๏Destructor is a member function which destructs or deletes an object.
๏They are called when the class object goes out of scope such as when the
function ends, the program ends, a delete variable is called etc.
A. Special Characteristics of destructors:
a) Name should begin with tilde sign(~) and must match class name.
b) Unlike constructors that can have parameters, destructors do not allow any
parameter.
c) They do not have any return type, just like constructors.
d) There cannot be more than one destructor in a class.
e) When you do not specify any destructor in a class, compiler generates a
default destructor and inserts it into your code.
Dr. Mirza Waseem Hussain 2
3. B. Declaration and Definition of destructors
Syntax:
class class_name{
public: // Access Specifier.
class_name(); // Declaration of constructor.
~class_name(); //Delaration of Destructor.
};
class_name::class_name(){ //Definition of constructor
}
class_name:: ~class_name(){ //Definition of destructor
}
int main()
{ class_name obj;
return 0;
}
Dr. Mirza Waseem Hussain 3
4. โข E.g.:1
#include <iostream>
using namespace std;
class student{
public: // Access Specifier.
student(); // Declaration of constructor.
~student(); //Delaration of Destructor.
};
student::student(){ //Definition of constructor
cout<<"Constructor called"<<endl; }
student:: ~student(){ //Definition of destructor
cout<<"Destructor called"<<endl; }
int main(){ student obj,obj1,obj2; return 0;}Dr. Mirza Waseem Hussain 4
5. Dr. Mirza Waseem Hussain 5
Constructor
of obj
Constructor
of obj1
Constructor
of obj2
Destructor of
obj2
Destructor of
obj1
Destructor of
obj
Order of Execution