Destructor
What is a Destructor?
In C++, a destructor is a special member function that is automatically called when an object goes out of scope or is explicitly deleted. Its primary purpose is to clean up resources or perform actions before the object’s memory is deallocated.
Destructor Charachteristics:
- Name and Syntax:
Name: Destructors have the same name as the class, preceded by a tilde (~).
Syntax: ~ClassName() - Automatic Invocation:
Destructors are automatically invoked when an object goes out of scope or is explicitly deleted.
They handle the cleanup and deallocation of resources held by the object. - No Return Type or Parameters:
Destructors don’t have a return type, not even void.
They do not accept any parameters. - Single Destructor per Class:
Each class can have only one destructor.
It’s responsible for cleaning up resources allocated during the object’s lifetime. - Manual Deletion:
For objects created dynamically using new, the destructor is called explicitly using delete.
This is essential for releasing memory allocated on the heap. - Resource Cleanup:
Destructors are often used to release resources such as dynamic memory, file handles, database connections, etc.
Ensures proper cleanup before the object is destroyed.
Why Use Destructors?
Destructors are essential for proper resource management and maintaining the integrity of your program. They are particularly useful when dealing with dynamic memory allocation, file handling, or any situation where cleanup is necessary.
Syntax of a Destructor:
The syntax for a destructor is straightforward. It has the same name as the class preceded by a tilde (~). Here’s an example:
class MyClass { public: // Constructor MyClass() { // Constructor code } // Destructor ~MyClass() { // Destructor code } };
Example 1:
#include <iostream> using namespace std; class Rectangle { private: int W, H; public: Rectangle(int a, int b) { W = a; H = b; cout << "A rectangle has been created\n"; } ~Rectangle() { cout << W << " " << H << " A rectangle has been deleted\n"; } }; int main() { Rectangle R1(3, 4), R2(5, 6); return 0; }
This code defines a class Rectangle representing a rectangle with private member variables W (width) and H (height). The class includes a constructor for creating a rectangle and a destructor for cleaning up resources when the rectangle is deleted. Let’s break down the code:
– Class Definition: Rectangle
class Rectangle { private: int W, H; public: // Constructor Rectangle(int a, int b) { W = a; H = b; cout << "A rectangle has been created\n"; } // Destructor ~Rectangle() { cout << W << " " << H << " A rectangle has been deleted\n"; } };
- Constructor:
Initializes the W (width) and H (height) member variables with the values passed as arguments.
Prints a message indicating that a rectangle has been created. - Destructor:
Prints a message with the dimensions of the rectangle when it is deleted.
– main Function:
int main() { // Creating two objects of class Rectangle Rectangle R1(3, 4), R2(5, 6); return 0; }
- Object Creation:
Two objects, R1 and R2, of type Rectangle are created in the main function. - Constructor Execution:
The constructor of the Rectangle class is executed for each object, initializing their width and height.
Messages are printed indicating that rectangles have been created. - Object Destruction:
When the program exits, or when the main function scope is left, the destructors for R1 and R2 are automatically called.
Messages are printed indicating that rectangles have been deleted, along with their dimensions.
The output of this program would be:
A rectangle has been created A rectangle has been created 5 6 A rectangle has been deleted 3 4 A rectangle has been deleted
This output demonstrates the automatic invocation of the constructor when objects are created and the destructor when objects go out of scope (at the end of the program in this case). The destructor prints messages indicating the deletion of rectangles along with their dimensions.
Example 2:
#include <iostream> using namespace std; class Rectangle { private: int W, H; public: Rectangle(): W(0), H(0) { cout << "W = " << W << " H = " << H << endl; } Rectangle(int a, int b): W(0), H(0) { W = a; H = b; cout << "A rectangle has been created\n"; Rectangle ob; } ~Rectangle() { cout << W << " " << H << " A rectangle has been deleted\n"; } }; int main() { Rectangle R1(3, 4), R2(5, 6); Rectangle R3; return 0; }
- Default Constructor:
Initializes W and H to 0.
Prints the initial values of W and H when an object is created with this constructor. - Parameterized Constructor:
Accepts parameters a and b to set the dimensions of the rectangle.
Initializes W and H to 0 before assigning the provided values.
Prints a message indicating that a rectangle has been created.
Creates another object ob inside the constructor (not recommended in general practice). - Destructor:
Prints a message with the dimensions of the rectangle when it is deleted.
The output of this program would be:
A rectangle has been created W = 0 H = 0 0 0 A rectangle has been deleted A rectangle has been created W = 0 H = 0 0 0 A rectangle has been deleted W = 0 H = 0 0 0 A rectangle has been deleted 5 6 A rectangle has been deleted 3 4 A rectangle has been deleted
Example 3:
#include <iostream> using namespace std; class phone { private: char name[10]; char model[10]; int price; public: phone() {} phone(char n[], char m[], int p) { strcpy(name, n); strcpy(model, m); price = p; } void print(); ~phone(); }; phone::~phone() { cout << "object destructed\n" } void phone::print() { cout << "Name = " << name << endl; cout << "Model = " << model << endl; cout << "Price = " << price << endl; } int main() { phone ob1, ob2("HUAWI", "MATE 9", 400); ob2.print(); return 0; }
This code defines a class phone representing a phone with private member variables name, model, and price. The class includes a default constructor, a parameterized constructor, a member function (print), and a destructor. Let’s break down the code:
– Class Definition: phone
class phone { private: char name[10]; char model[10]; int price; public: // Default Constructor phone() {} // Parameterized Constructor phone(char n[], char m[], int p) { strcpy(name, n); strcpy(model, m); price = p; } // Member Function to Print Phone Details void print(); // Destructor ~phone(); };
- Default Constructor:
An empty default constructor is provided. - Parameterized Constructor:
Accepts parameters n (name), m (model), and p (price) to initialize the object’s member variables. - Member Function (print):
Displays the details of the phone, including its name, model, and price. - Destructor:
Outputs a message when an object of the class is destructed.
– Destructor Implementation:
phone::~phone() { cout << "object destructed\n"; }
The destructor is defined outside the class and prints a message when an object of the class is destructed.
– main Function:
int main() { phone ob1, ob2("HUAWI", "MATE 9", 400); ob2.print(); return 0; }
- Object Creation:
Two objects, ob1 and ob2, of type phone are created.
ob2 is initialized using the parameterized constructor. - Printing Details:
The print member function is called for ob2 to display its details. - Object Destruction:
When the program exits, or when the main function scope is left, the destructors for ob1 and ob2 are automatically called.
A message is printed indicating that an object has been destructed.
The output of this program would be:
Name = HUAWI Model = MATE 9 Price = 400 object destructed
This output demonstrates the creation, printing, and destruction of phone objects, including the use of the parameterized constructor and the destructor.
Example 4:
#include <iostream> #include <cstring> using namespace std; class Student { private: char name[20]; int ID; public: Student() { cout << "Object created\n"; } ~Student() { cout << "Object destructed\n"; } void Set_Name_ID(char n[], int id) { strcpy(name, n); ID = id; } void print(void) { cout << name << "\t" << ID << endl; } }; //end of class definition void F(Student S) { Student S1; S1 = S; S.Set_Name_ID("Sami", 12345); S.print(); S1.print(); } int main() { Student St1, St2; St1.Set_Name_ID("Ahmad", 11111); St2.Set_Name_ID("Ali", 22222); cout << "Going to Function\n"; F(St1); cout << "Back from Funcrion\n"; St1.print(); return 0; }
This code defines a class Student representing a student with private member variables name and ID. The class includes a default constructor, a destructor, a member function to set the name and ID, and another member function to print the student’s details. Additionally, there is a function F that takes a Student object as a parameter and demonstrates object creation, assignment, modification, and destruction within a function. Let’s break down the code:
– Class Definition: Student
class Student { private: char name[20]; int ID; public: // Default Constructor Student() { cout << "Object created\n"; } // Destructor ~Student() { cout << "Object destructed\n"; } // Member Function to Set Name and ID void Set_Name_ID(char n[], int id) { strcpy(name, n); ID = id; } // Member Function to Print Student Details void print(void) { cout << name << "\t" << ID << endl; } };
- Default Constructor:
Prints a message indicating that an object has been created. - Destructor:
Prints a message indicating that an object has been destructed. - Set_Name_ID Function:
Accepts parameters n (name) and id (ID) to set the member variables. - print Function:
Prints the name and ID of the student.
– Function F:
void F(Student S) { Student S1; S1 = S; S.Set_Name_ID("Sami", 12345); S.print(); S1.print(); }
- Creates a Student object S1 within the function.
- Copies the content of the parameter S into S1.
- Modifies the content of S using the Set_Name_ID function.
- Prints the details of both S and S1.
– main Function:
int main() { Student St1, St2; St1.Set_Name_ID("Ahmad", 11111); St2.Set_Name_ID("Ali", 22222); cout << "Going to Function\n"; F(St1); cout << "Back from Function\n"; St1.print(); return 0; }
- Object Creation and Modification:
Creates two Student objects, St1 and St2.
Sets their names and IDs using the Set_Name_ID function. - Function Call:
Calls the function F passing St1 as a parameter. - Object Destruction:
Prints messages indicating the destruction of objects when they go out of scope (end of the function or program).
The output of this program would be:
Object created Object created Going to Function Object created Sami 12345 Ahmad 11111 Object destructed Object destructed Back from Funcrion Ahmad 11111 Object destructed Object destructed
This output demonstrates the creation, modification, and destruction of Student objects, including the behavior of the default constructor and destructor. The F function illustrates object copying and modification within a function.