Hi i am new to the discussion forum and i want to learn cpp.
Why destructor with ~ is used in cplus-plus coding for every constructor?

Thanks

Well, destructors are mainly used to de-allocate memory that was allocated to the object by constructor or cleanup of object members. They are not compulsory, that is you have should have it with every constructor. Perhaps you use it as I mentions when you dynamically allocate memory.

Destructors are called after the object passes out of scope or is explicitly deleted.

http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/cplr380.htm

As mentioned, destructors are for freeing resources when an object is being deleted. If the object only uses non-dynamically assigned resources, the destructor will do nothing (this is also the default if you don't explicitly code one). If you do use dynamic allocation for any member data, those need to be freed in the destructor or eles you'll have memory leaks - the default doesn't work here.

As to why it uses the ~, well, I guess that was the decision of the guy who wrote C++. My guess is that the ~ (two's complement) of the constuctor is the destructor, but that's just what my tired brain is making up... :p

>Why destructor with ~ is used in cplus-plus coding for every constructor?
~ is the complement operator in C++, and a destructor is the complement of a constructor. The creator of the language admits that this may have been "overly clever", and I agree thoroughly, but at this point there's nothing we can do about it.

For questions like that about the how and why of C++'s design, there's a book by the creator called "The Design and Evolution of C++".

This article has been dead for over six months. Start a new discussion instead.