Constructors and Destructors
What is a Constructor?
A constructor is a special member function of a class that is automatically called when an object is created.
google.com, pub-8434817042454839, DIRECT, f08c47fec0942fa0
It is mainly used to initialize values.
Key Features of Constructor
- Same name as class
- No return type (not even
void) - Called automatically
- Can be overloaded
Basic Example
#include<iostream>
using namespace std;
using namespace std;
class Student {
public:
Student() {
cout << “Constructor called”;
}
};
int main() {
Student s1;
return 0;
}
Parameterized Constructor
Used to pass values during object creation
class Student {
public:
int age;
public:
int age;
Student(int a) {
age = a;
}
};
int main() {
Student s1(20);
cout << s1.age;
}
Constructor Overloading
Multiple constructors with different parameters
class Student {
public:
Student() {
cout << “Default Constructor\n“;
}
public:
Student() {
cout << “Default Constructor\n“;
}
Student(int a) {
cout << “Parameterized Constructor”;
}
};
What is a Destructor?
A destructor is a special function that is automatically called when an object is destroyed.
Used to free memory / clean resources
Key Features of Destructor
- Same name as class
- Starts with
~symbol - No parameters
- Only one destructor per class
Example
class Student {
public:
~Student() {
cout << “Destructor called”;
}
};
public:
~Student() {
cout << “Destructor called”;
}
};
int main() {
Student s1;
return 0;
}
Real-Life Example (Very Important for Understanding)
class Student {
public:
Student() {
cout << “Object Created\n“;
}
public:
Student() {
cout << “Object Created\n“;
}
~Student() {
cout << “Object Destroyed”;
}
};
int main() {
Student s1;
}
Output:
Object Created
Object Destroyed
Object Destroyed
When are Constructors & Destructors Called?
- Constructor → when object is created
- Destructor → when object goes out of scope
Why This is Important?
- Helps in automatic initialization
- Manages memory properly
- Used in real-world applications

