C++ Destructors
A destructor in C++ is a special member function of a class that is automatically called when an object goes out of scope or is explicitly deleted. Destructors are used to release resources, such as memory or file handles, that were acquired by the object. They have the same name as the class, preceded by a tilde (~), and do not have a return type or parameters.
Syntax
class ClassName {
public:
~ClassName() {
// Code to release resources
}
};
Example: Destructor
#include <iostream>
using namespace std;
class Student {
public:
string name;
Student(string n) { // Constructor
name = n;
cout << "Constructor called for " << name << endl;
}
~Student() { // Destructor
cout << "Destructor called for " << name << endl;
}
};
int main() {
Student s1("Alice"); // Constructor called
Student s2("Bob"); // Constructor called
cout << "Inside main function" << endl;
return 0; // Destructors called automatically for s1 and s2
}
Output
Constructor called for Alice Constructor called for Bob Inside main function Destructor called for Bob Destructor called for Alice
Important Notes
- Destructors have the same name as the class, preceded by a tilde (
~), and do not take parameters. - Destructors are called automatically when an object goes out of scope or is deleted.
- They are commonly used to release dynamically allocated memory or other resources.
Next Topic
Next, learn about Access Specifiers in C++.