+ 1

Need of destructor

How do I know if I need a destructor for a class?

12th Dec 2017, 10:32 PM
crackle
crackle - avatar
8 odpowiedzi
+ 11
Maybe you forgot classes always have destructors, evenif you dont insert the function ~classname() the compiler creates a default destructor. The destructor is called automatically when the object goes out of scope. This happens when the function, the program or a block containing local variables ends. Or if a delete operator is called. You can write your own desstructor for example to check if the object is destroyed. Or if you have DYNAMICALLY allocated memory inside your class. In this case you have to manually manage the resources. This is the most important use of destructors. Hope it helps
13th Dec 2017, 12:28 AM
AZTECCO
AZTECCO - avatar
+ 9
hey @crackle why did you marked your own answer? wouldn't be better if you mark one we provided.. ?
3rd Jan 2018, 4:55 PM
AZTECCO
AZTECCO - avatar
+ 8
Thank you! :)
4th Jan 2018, 8:32 AM
AZTECCO
AZTECCO - avatar
+ 6
As John said the deconstructors are used to free dynamically allocated memory that you are responsible for. They also have many other uses on the other hand. They can be used to clean up or adjust other tables that have used the object and any other number of potential uses.
12th Dec 2017, 11:23 PM
Michael Simnitt
Michael Simnitt - avatar
+ 5
To elaborate on what both John and Michael said, here's an example of a class that would need a destructor: class MyClass { public: int* myNum; MyClass() { myNum = new int[10] }; ~MyClass() { delete [] myNum; } };
12th Dec 2017, 11:59 PM
Zeke Williams
Zeke Williams - avatar
+ 4
I should have stated the question a little more accurately, but you have already answered my question: When should I define a deconstructor? Thanks a lot! :-)
13th Dec 2017, 6:59 AM
crackle
crackle - avatar
+ 3
I'm going to assume C++. But it applies for all languages that can allocate memory and you are responsible to return it. When you allocate storage within the class with malloc or new either in constructor or later. Your destructor must free that storage as the default one won't know it needs to be.
12th Dec 2017, 11:00 PM
John Wells
John Wells - avatar
+ 3
AZTECCO has a great point. It's the same for copy constructors and constructors as well. I think someone told me if you have to define a destructor or copy constructor yourself, you should also be defining the other. I think it's called the rule of three's. Maybe it was four's I can't remember.
13th Dec 2017, 12:40 AM
Zeke Williams
Zeke Williams - avatar