Saturday, May 22, 2010

When do we use destructors in C++?

when we use private pointers, private arrays or allocating dynamic memory. I thought that only when something dynamically allocated we need to delete it, to free memory and avoid memory leaks.


however, my friend told me that in all of the above cases destructors are used.


could someone clarify?


appreciate that!

When do we use destructors in C++?
Your friend is right. Whenever a variable goes out of scope, or is deleted, the destructor is automatically called.





Remember it this way: let's say that you have a class and in its constructor memory was allocated... How would a statically allocated object release that memory when the object is destroyed (because it goes out of scope)? It can only do that through the constructor (or, admittedly, through a member function that is used as a destructor, but that's merely semantics...).





In other words, any statically allocated variable can contain dynamically allocated data, and it has to be released at some point.
Reply:Actually Destructors are almost opposite of constructors. Whenever you define a constructor it is a good practice to define its destructor to free the memory after your work would be done. You are right that they are compulsorily used to free dynamically allocated memory but this is not the only case where destructor's may be used
Reply:you are correct. Only when memory is alocated does it need to be deconstructed.


No comments:

Post a Comment