We’ve looked at Constructors in C++ to create an object, and building an object with new. However, what happens when we no longer need that object? That’s where a destructor is called. It is built into all objects, and if you don’t define one, a default one will be called for you.
The destructor’s job is to clean up any created objects… while the run time will automatically do that for you, it doesn’t necessarily do that with objects that contain objects, especially if you called new to create a pointer to an object. So you need to call their destructors directly within your destructor.
If you do not delete your old objects, you get memory leaks, areas of memory which cannot be accessed because the program thinks that data is still being used. As your program gets larger, more complex, and runs longer, it continues to grow until all resources are taken up.
These are not uncommon, but can cause lots of issues. I routinely have to shut down my browsers because they consume 3 to 4 GB of memory (I like to have lots of tabs open.)
When you exit an application, either through a standard exit process, because the program reaches the end of the application, or because of an error, all memory consumed gets returned to the OS… but we’d not like to have to rely on that if possible.
Luckily creating a destructor is simple. Calling another object’s desctrutor is really simple as well. Let’s start with a situation. Consider the Circle Class we’ve been working with. Consider that it has an property which is an object, called location. Location is an object, of type Point which holds the x and y coordinates for where the center of the circle is located.
Based upon that info, we need to delete that object.
The Destructor in C++ has the same name as the Constructor, except it starts with a tilde (~). Like the Constructor, is does not return a data type.
Circle::~Circle()
{
numOfObjects--; // delete 1 from the static object
// this helps keep an accurate number of active objects
delete location; // this calls the destructor of the location object.
}
Notice the use of the delete keyword. This deletes the object. This can be done from within an application as well as within the object for a child object.
Destructors in C++ was originally found on Access 2 Learn
One Comment
Comments are closed.