I am relatively new to C++ (and programming in general) so please forgive me if the question is not perfectly clear immediately.
What I have is a program in which a certain number of objects of a internally defined class [let's call this "class1"] are created. The program works perfectly fine and the objects do what they should.
The problem that I am currently trying to solve is the following: these objects are not destroyed (and thus memory is not de-allocated) until the program exits, but I need that memory earlier.
Among the other members of the class there are objects of other internally defined classes (who also have members that are objects of a third class).
My question is the following: how do I properly define a destructor for the objects of "class1" so that all the data is cancelled and the memory deallocated?
I found out (probably this was obvious for you already) that a destructor like
class1::~class1(void) {
}
won't work (I defined similar destructors for all internally defined classes).
Reading around I understood that my mistake could be that that is a destructor that does nothing. How do I solve this?
Thanks to anyone who will answer/help/comment.
Federico
In C++ you need to free the memory manually. There's no garbage collector. You obviously need to free the memory manually inside your destructor. If you allocated the memory using new, you need to use delete for each resource you allocated with new inside the deconstructor, for example:
class1::~class1(void)
{
delete resource1;
delete resource2;
etc...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With