Constructors and Destructors
A constructor is a special function that is called automatically when an object is created. It is used to initialize the object's data members. The constructor's name must be the same as the class name and has no return type, not even void.
A destructor is a special function that is called automatically when an object is destroyed or leaves scope. Destructors are used to clean up resources that were allocated during the object's lifetime. A destructor is marked with a ~ before the class name.
Code Example
#include <iostream>
#include <string>
using namespace std;
class Resource {
private:
string data;
int* buffer;
public:
Resource() {
data = "Default";
buffer = new int[10];
cout << "Default constructor called" << endl;
}
Resource(string initData) {
data = initData;
buffer = new int[10];
cout << "Parameterized constructor called: " << data << endl;
}
Resource(string initData, int bufferSize) {
data = initData;
buffer = new int[bufferSize];
cout << "Constructor with multiple parameters called: " << data << endl;
}
Resource(const Resource& other) {
data = other.data;
buffer = new int[10];
for (int i = 0; i < 10; i++) {
buffer[i] = other.buffer[i];
}
cout << "Copy constructor called" << endl;
}
~Resource() {
delete[] buffer;
cout << "Destructor called: " << data << endl;
}
void display() {
cout << "Data: " << data << ", Buffer address: " << buffer << endl;
}
};
int main() {
cout << "=== Creating first object ===" << endl;
Resource res1;
res1.display();
cout << "\n=== Creating second object ===" << endl;
Resource res2("Important Data");
res2.display();
cout << "\n=== Creating third object ===" << endl;
Resource res3("Application Config", 20);
res3.display();
cout << "\n=== Creating fourth object (copy) ===" << endl;
Resource res4 = res2;
res4.display();
cout << "\n=== Program finished, objects destroyed ===" << endl;
return 0;
}
Code Explanation
-
Resource()- The default constructor (no parameters). Called when an object is created without arguments. Initializes the data members with default values. -
Resource(string initData)- A parameterized constructor. Takes one parameter to initialize a data member with a specific value. -
Resource(string initData, int bufferSize)- A constructor with two parameters. Allows more flexible initialization. -
Resource(const Resource& other)- The copy constructor. Called when a new object is created from an existing object. Theconst referenceparameter is used to avoid an unnecessary copy. -
~Resource()- The destructor. Called when the object is destroyed. Its job is to free the memory allocated withnew. -
delete[] buffer- Cleans up the dynamic array inside the destructor. Important to prevent a memory leak. -
The order of the output shows that constructors are called when objects are created, and destructors are called in reverse order when the program ends.
Everyday Use Cases
Imagine a hotel. When a guest checks in (constructor), the hotel prepares the room, towels, and amenities for that guest. During the stay, the guest uses the room's facilities. At check-out (destructor), the hotel cleans the room, takes the towels away, and prepares the room for the next guest. A copy constructor is like two guests wanting a room with exactly the same contents.
Conclusion
Constructors are called automatically when an object is created to initialize data. Destructors are called automatically when an object is destroyed to clean up resources. C++ supports constructor overloading (many versions with different parameters). A copy constructor is used to create a new object from an existing one. The order of destruction is the reverse of the order of construction.