When working with classes, you often need to set initial values for an object's attributes as soon as it is created. Similarly, when the object is no longer needed, you may need to free up memory or release resources. This is handled by Constructors and Destructors.
A constructor is a special member function that is automatically called when an object of a class is created. Its primary purpose is to initialize the data members of the new object.
void.public section.#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int age;
// 1. Default Constructor (No parameters)
Student() {
name = "Unknown";
age = 0;
cout << "Default constructor called!" << endl;
}
// 2. Parameterized Constructor
Student(string n, int a) {
name = n;
age = a;
cout << "Parameterized constructor called for " << name << endl;
}
};
int main() {
Student s1; // Calls default constructor
Student s2("Alice", 20); // Calls parameterized constructor
return 0;
}Just like regular functions, constructors can be overloaded. This means a class can have multiple constructors as long as their parameter lists (signatures) are different. This allows objects to be initialized in various ways.
A destructor is a special member function that is automatically called when an object goes out of scope or is explicitly deleted. Its purpose is to clean up resources (like closing files or freeing dynamically allocated memory) before the object is destroyed.
~).class DatabaseConnection {
public:
// Constructor
DatabaseConnection() {
cout << "Opening database connection..." << endl;
}
// Destructor
~DatabaseConnection() {
cout << "Closing database connection to free resources." << endl;
}
};
int main() {
{
DatabaseConnection db; // Constructor is called here
// ... use db ...
} // Object 'db' goes out of scope here; Destructor is called automatically
cout << "Program ends." << endl;
return 0;
}~ and cannot take arguments.A special member function invoked automatically when an object is created, used to initialize the object.
A special member function invoked automatically when an object is destroyed, used to release resources.
A class can have multiple constructors with different parameters, allowing objects to be initialized in different ways.
Test your understanding with 3 questions
Which of the following is true about a constructor?
What is the symbol used to denote a destructor?
Can a class have multiple destructors?
2 Modules
2 Modules