Destructor

I know that the destructor is used to free the dynamically allocated memory. Is it also correct to say that the destructor is used for destroying an object?

If you write a class within an instance of which you allocate memory on the heap, then it is the responsibility of that class to clear the allocated memory before its instance goes out of scope. This is done in its destructor.
Thanks you for the answer but my question was
Is it correct to say that the destructor is used for destroying an object?
Yes it correct. This is the exact wording used by the C++ standard:

The C++11 standard (ยง12.4/2)
A destructor is used to destroy objects of its class type.
Last edited on
it is the responsibility of that class to clear the allocated memory before its instance goes out of scope. This is done in its destructor.
I want to chime in and say that it is incorrect. Destructor does not frees the memory, it just destroys object. Memory is still here and you can reuse it (if memory itself is not deleted, say, by delete operator). It cannot possibly know how to actually release memory (delete? free? some allocator-specific method?) as method to do so is not stored in class.

I want to chime in and say that it is incorrect. Destructor does not frees the memory, it just destroys object. Memory is still here and you can reuse it (if memory itself is not deleted, say, by delete operator). It cannot possibly know how to actually release memory (delete? free? some allocator-specific method?) as method to do so is not stored in class.


Thanks for your input, obviously you need to write the code in the destructor to delete the allocated memory etc, I didn't mean that the destructor will just do it for you!
Topic archived. No new replies allowed.