Constructor and Destructor in C++ - Explained in Simple Words
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,…
Constructor and Destructor in C++ are special functions of a class that are automatically called when an object is created or destroyed. You do not need to call them yourself; C++ takes care of this for you.
A Constructor is a special function that runs automatically when we create an object. Its purpose is to initialize the object. The constructor's name is the same as the class name and it has no return type, not even void. For example, in a Student class, the constructor might set the initial values for name, roll number, and marks.
Rules of Constructor include having the same name as the class, no return type, and being called automatically when an object is created. An example of a constructor in C++ would be:
```cpp
include using namespace std;
class Student {
public:
string name;
Student() {
cout << "Constructor Called!" << endl;
name = "Aliza";
}
};
```
In contrast, a Destructor is the opposite of a Constructor. It is called automatically when an object is destroyed or the program ends. The purpose of a Destructor is to clean up memory, such as closing a file or freeing memory that was previously allocated.
Rules of Destructor include having the same name as the class but with a tilde (~) sign, also having no return type, and being called automatically at the end of the program. An example of a destructor in C++ would be:
```cpp
include using namespace std;
class Student {
public:
Student() {
cout << "Constructor Called" << endl;
}
~Student() {
cout << "Destructor Called" << endl;
}
};
```
In summary, Constructors run at the START when an object is created, and their job is to initialize it, while Destructors run at the END when an object is destroyed, working to clean up any resources. Both are essential for making programs easier to write and easier to manage, as they automate the process of initializing and cleaning up objects.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.