What is a Constructor?
A constructor is a special member function that gets automatically invoked when an object is created. It initializes the object.
Features:
- Same name as the class.
- No return type (not even void).
- Allows overloading (multiple constructors with varying parameter lists).
Example:
#include
using namespace std;
class Car {
public:
Car() {
cout << “Constructor called: Car object created” << endl;
}
};
int main() {
Car myCar; // Constructor is automatically called here
return 0;
}
Types of Constructors:
- Default Constructor– No parameters.
- Parameterized Constructor– Accepts arguments.
- Copy Constructor– Creates a copy of an existing object.
Parameterized Constructor Example:
class Car {
string model;
public:
Car(string m) {
model = m;
cout << “Car model: ” << model << endl;
}
};
Copy Constructor Example:
class Car {
string model;
public:
Car(string m) {
model = m;
}
Car(const Car &c) {
model = c.model;
cout << “Copy constructor called for model: ” << model << endl;
}
};
What is a Destructor?
A destructor is a special member function that gets automatically called when an object is destroyed. It cleans up memory/resources.
Features:
- Same name as the class but prefixed with a tilde ~.
- No parameters and no return type.
- Cannot be overloaded.
Example:
class Car {
public:
Car() {
cout << “Constructor called.” << endl;
}
~Car() {
cout << “Destructor called.” << endl;
}
};
int main() {
Car myCar;
return 0;
}
When the program ends or the object goes out of scope, the destructor is invoked.
Constructor vs Destructor
Feature | Constructor | Destructor |
Purpose | Initializes the object | Cleans up before destruction |
Invocation | When object is created | When object is destroyed |
Parameters | Can have parameters | Cannot have parameters |
Overloading | Yes | No |
Why Are They Important?
- Ensures every object is properly initialized (constructor).
- Prevents memory leaks and resource mishandling (destructor).
- Essential in classes that use dynamic memory allocation(new/delete).
Real-Life Use Case: Dynamic Memory
class DynamicArray {
int* arr;
public:
DynamicArray(int size) {
arr = new int[size]; // allocate memory
cout << “Memory allocated.” << endl;
}
~DynamicArray() {
delete[] arr; // deallocate memory
cout << “Memory deallocated.” << endl;
}
};
This pattern is common in resource-managing classes — making destructors crucial.
Constructors and destructors are key to mastering C++ OOP. They automate the setup and cleanup of objects, reducing manual errors and improving code clarity. Understanding them is the first step toward writing efficient, safe, and clean C++ code.