The compiler usually creates one for you. This is compiler-dependent. I am a beginner in programming, and the only times I use a destructor is when I need to delete allocated memory when an object of a class is destroyed.
When making a class, define the destructor even if there is nothing in it. It is convention to have the "rule of three" or the "big four", which is the copy constructor, overloaded assignment operator, and destructor. Some also believe a default constructor must always be made even though the compiler will make one for you.
--EDIT--
Here is an example: Say you allocated memory to an integer pointer somewhere in your object
1 2 3 4 5
|
//private attribute
int* ptr
//In some member function of the object
ptr = new int[250];
| |
When that object is destroyed, the memory you allocated will be leaked, and leaking memory is bad.
Therefore, your destructor for the class should look something like this
1 2 3 4
|
className::~className()
{
delete [] ptr;
}
| |
This "gives back the memory". It probably won't affect you now, but leaking memory in bigger programs can lead to a computer running out of memory and crashing.