What is Constructor and Destructor in C++?
In C++, Constructor and Destructor are special functions of a class. They are automatically called when we create or destroy an object.
You do not need to call them yourself. C++ calls them for you.
What is Constructor?
Constructor is a special function that runs automatically when we create an object.
Its work is to initialize the object. For example, to set the starting value of name, roll no, marks.
Rules of Constructor:
- Constructor name is same as Class name.
- It has no return type, not even void.
- It is called automatically when object is created.
Example of Constructor:
include
using namespace std;
class Student {
public:
string name;
// Constructor
Student() {
cout << "Constructor Called! Object Created" << endl;
name = "Aliza";
}
};
int main() {
Student s1; // Constructor will run automatically here
cout << "Name is: " << s1.name;
return 0;
}
Output:
Constructor Called! Object Created
Name is: Aliza
What is Destructor?
Destructor is opposite of Constructor. It runs automatically when object is destroyed or program ends.
Its work is to clean up memory. For example, to close a file or free memory.
Rules of Destructor:
- Destructor name is same as Class name but with ~ sign.
- It also has no return type.
- It is called automatically at the end.
Example of Destructor:
include
using namespace std;
class Student {
public:
Student() {
cout << "Constructor Called" << endl;
}
// Destructor
~Student() {
cout << "Destructor Called" << endl;
}
};
int main() {
Student s1;
cout << "Inside Main Function" << endl;
return 0;
}
Output:
Constructor Called
Inside Main Function
Destructor Called
Constructor vs Destructor - Easy Difference:
Constructor: Runs at START, when object is created. Work is to initialize.
Destructor: Runs at END, when object is destroyed. Work is to clean up.
Conclusion:
Constructor helps us to set the starting values. Destructor helps us to clean up. Both make our program easy and automatic.
I have tested this code myself and it works perfectly.
Top comments (0)