Question:
what is the importance of destructor in c++?
supravat
2010-03-15 18:26:14 UTC
what is the importance of destructor in c++?
Four answers:
Allan
2010-03-15 21:17:58 UTC
Constructor and Destructor functions are Member Functions of a class having

some special property.



Constructor function is used to initialize member variables to pre-defined

values as soon as an object of a class is declared.



Constructor function gets invoked when an object of a class is constructed

(declared).



So basically Constructor is used to initialize the objects (at the time of creation), and they are automatically invoked.



This saves us from the garbage values assigned to data members; during initializing.





Destructors have the opposite function of a constructor. The main use

of destructors is to release dynamic allocated memory. Destructors are

used to free memory, release resources and to perform other clean up.

Destructors are automatically named when an object is destroyed. Like

constructors, destructors also take the same name as that of the class

name.
Robin T
2010-03-15 18:58:40 UTC
To Leo (the answerer before me), no, that's not what destructor is for. C++ has its "garbage collector" that frees up memory automatically once an object or variable is no longer used.



You use destructor to do things that are not handled by the garbage collector like closing a database connection, freeing a file locking, closing socket or any other methods of remote connections, etc.
vaisakh
2010-03-16 06:09:51 UTC
a destructor is a special member function of a class. it is invoked automatically whenever an object of the class goes out of scope, i.e., gets 'destroyed'. thus destructors provide a useful way to do things you might want to while winding up, like freeing up memory, closing database connections, network connections etc. like a constructor, a destructor does not have a return type, but unlike a constructor, it does not take any arguments.
Leo R
2010-03-15 18:35:47 UTC
If you let variables lie around occupying space, and you create a lot of them through recursion or large arrays, the memory does not get reclaimed, and the memory required by the process gets larger and larger, eventually possibly leading to a program crash. This is called a "memory leak" to allocate memory and never give it back. In processes that run a long time, like a driver or a web service, this can cause problems at the OS level with resource hogging.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...