+ 1
Need of destructor
How do I know if I need a destructor for a class?
8 Respuestas
+ 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
+ 9
hey @crackle why did you marked your own answer? wouldn't be better if you mark one we provided.. ?
+ 8
Thank you! :)
+ 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.
+ 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; }
};
+ 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! :-)
+ 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.
+ 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.