Constructors & Destructors
Definition
A constructor is a special member function of a class that is automatically called when an object of that class is created. Its main purpose is to initialize the object's data members and prepare it for use.
A destructor is a special member function of a class that is automatically called when an object is destroyed or goes out of scope. Its main purpose is to free resources, clean up memory, and perform final object-related tasks.
Both constructors and destructors have the same name as the class in many languages like C++, but the destructor is usually prefixed with a tilde ~. They do not return any value.
Main Content
1. Constructors
- Constructors are automatically invoked at the time of object creation, so the programmer does not need to call them explicitly.
- They are used to assign initial values to data members, allocate memory dynamically if required, and ensure the object begins in a valid state.
A constructor can be of different types, such as:
Default constructor
- : takes no parameters and initializes objects with default values.
Parameterized constructor
- : takes arguments and initializes objects with user-defined values.
Copy constructor
- : creates a new object by copying an existing object.
Example in C++:
#include <iostream>
using namespace std;
class Student {
int roll;
string name;
public:
Student() { // default constructor
roll = 0;
name = "Unknown";
}
Student(int r, string n) { // parameterized constructor
roll = r;
name = n;
}
void display() {
cout << roll << " " << name << endl;
}
};
int main() {
Student s1;
Student s2(101, "Amit");
s1.display();
s2.display();
return 0;
}
In this example, the constructor sets values automatically when the object is created.
2. Destructors
- Destructors are automatically executed when an object is about to be destroyed, such as when it goes out of scope or a program ends.
- They are mainly used to release resources like dynamically allocated memory, open files, database connections, or other system resources.
A destructor is very important when a class uses pointers or dynamic memory. If memory is allocated using new, it should usually be released in the destructor using delete to avoid memory leaks.
Example in C++:
#include <iostream>
using namespace std;
class Demo {
int *ptr;
public:
Demo() {
ptr = new int(10);
cout << "Constructor called" << endl;
}
~Demo() {
delete ptr;
cout << "Destructor called" << endl;
}
};
int main() {
Demo d;
return 0;
}
Here, the constructor allocates memory and the destructor releases it safely.
3. Key Features and Differences
- Constructors are used for initialization, while destructors are used for cleanup and resource release.
- Constructors can be overloaded, meaning a class can have multiple constructors with different parameter lists.
- A class can have only one destructor, and it cannot be overloaded because its purpose is fixed.
- Constructors are called at the beginning of an object’s life, while destructors are called at the end.
- Neither constructors nor destructors return any value, and neither can be declared as
static.
Important rules:
- Constructor name must match the class name.
- Destructor name is the class name preceded by
~. - Both are automatically called by the compiler.
- Destructor is particularly useful in classes handling dynamic resources.
Working / Process
1. Object creation triggers constructor
- When an object is declared, the compiler automatically identifies the appropriate constructor.
- If no arguments are provided, the default constructor is used.
- If arguments are provided, the matching parameterized constructor is called.
2. Initialization of data members
- The constructor assigns values to variables and may also allocate memory or open files.
- This ensures the object is ready for use immediately after creation.
- If inheritance is involved, constructors of base classes are called first, followed by derived class constructors.
3. Object destruction triggers destructor
- When an object goes out of scope or is explicitly destroyed, the destructor is called automatically.
- It releases allocated memory and performs cleanup tasks.
- In inheritance, destructors are called in reverse order: derived class destructor first, then base class destructor.
Advantages / Applications
- Constructors ensure automatic initialization, reducing the chance of using uninitialized variables.
- Destructors help prevent memory leaks and resource misuse by cleaning up allocated memory and other resources.
- They improve program reliability, readability, and maintainability by organizing object life cycle management.
- Constructors and destructors are widely used in classes that handle files, dynamic memory, databases, network connections, and system-level resources.
- They are essential in object-oriented design, especially for real-world applications where proper resource handling is necessary.
Summary
- Constructors initialize objects automatically.
- Destructors clean up objects automatically.
- They help manage the full life cycle of class objects in a safe and organized manner.
- Constructors and destructors are essential for reliable object-oriented programming.