Constructors and Destructors
Constructors guarantee an object is properly initialized the moment it is born; destructors guarantee resources are cleaned up when it dies.
What is it?
• Constructor: A special member method called automatically upon object creation, sharing the exact class name and having NO return type. • Destructor: Called automatically when an object goes out of scope, prefixed with a tilde `~ClassName()`.
Why is it used?
Implements RAII (Resource Acquisition Is Initialization)—C++'s core memory safety paradigm guaranteeing zero leaks.
Detailed Explanation
Syntax Structure
class MyClass {
public:
MyClass(int val) : data(val) {} // Constructor
~MyClass() {} // Destructor
};
Code Example
#include <iostream>
#include <string>
class CourseSession {
private:
std::string course_title;
int active_students;
public:
// Parameterized Constructor using modern Member Initializer List
CourseSession(const std::string &title, int students)
: course_title(title), active_students(students) {
std::cout << "[CONSTRUCTOR] Initialized session for: " << course_title
<< " with " << active_students << " students.\n";
}
// Destructor: Automatically cleans up when object leaves scope
~CourseSession() {
std::cout << "[DESTRUCTOR] Closed session for: " << course_title
<< ". Resources released.\n";
}
void report() const {
std::cout << "Session Active: " << course_title << "\n";
}
};
int main() {
std::cout << "=== Entering main() ===\n";
// Block scope demonstration
{
CourseSession morning_batch("KLiC Advanced Python", 22);
morning_batch.report();
std::cout << "Exiting inner block scope...\n";
} // morning_batch destructor is called immediately here!
std::cout << "=== Ending main() ===\n";
return 0;
}
Explanation of the Code
Expected Output
Real-World Application
RAII powers smart pointers (`std::unique_ptr`), lock guards in multi-threaded servers, and database connection pools.
Common Mistakes to Avoid
Quick Practice Challenge
Create a `DatabaseConnection` class with a constructor printing 'Connected' and a destructor printing 'Disconnected'.