C++ destructors
Created By: chatGPT
Destructors in C++ are special member functions that are invoked when an object goes out of scope or is explicitly deleted. Their primary purpose is to free resources that the object may have acquired during its lifetime, such as dynamic memory, file handles, or network connections. A destructor has the same name as the class but is preceded by a tilde (~). There can only be one destructor per class, and it does not take any parameters or return a value.
class Example {
public:
Example() {
// Constructor code
}
~Example() {
// Destructor code, clean up resources
}
};
When an object is created, the constructor initializes it, and when the object is destroyed, the destructor is called automatically. In the case of stack-allocated objects, the destructor is called when the block is exited. For dynamically allocated objects (created with
new
), the destructor is called when delete
is invoked on the pointer.void function() {
Example obj; // Constructor called
} // Destructor called here when 'obj' goes out of scope
Example* ptr = new Example(); // Constructor called
delete ptr; // Destructor called here
If a class allocates memory or resources in its constructor, it is crucial to release those resources in the destructor. Failure to do so can lead to memory leaks. If a class contains pointers to other objects, its destructor should also delete those pointers to prevent memory issues.
class Resource {
public:
Resource() {
data = new int[100]; // Allocate memory
}
~Resource() {
delete[] data; // Clean up memory
}
private:
int* data;
};
In cases of inheritance, a base class should declare a virtual destructor. This ensures that the derived class's destructor is invoked correctly when an object of the derived class is deleted through a pointer of the base class. Not using a virtual destructor can lead to resource leaks if the derived class's destructor does not get called.
class Base {
public:
virtual ~Base() {
// Cleanup Base resources
}
};
class Derived : public Base {
public:
~Derived() {
// Cleanup Derived resources
}
};
Base* base = new Derived();
delete base; // Calls Derived's destructor followed by Base's