Reputation: 104
I was wondering what the difference is between a class destructor and just flat out deleting the class object. To me they look like they do the same thing so how do you chose which one to use?
For example, I'm working on a program where I need to delete some class objects that I created. I have a few class contructors like so VectorClass *v_temp1 = new VectorClass(v1, size);
and at the end of the function I have them deleted using just the delete v_temp1
call. It works just fine and the object is being deleted so why would I go through the trouble to create a destructor when I can just simply do that?
Upvotes: 2
Views: 1476
Reputation: 21003
Class destructor is called automatically whenever an object ceases to exist. So you cannot 'choose if to use it or not` - destructor call is built in the language. (Technically you can and sometimes you need to call destructor manually, but not in normal cases). You do not need to provide a destructor - but if you want to execute some code when objects of your class get destroyed destructor is the right place.
Operator delete
needs to be manually used whenever you no longer need an object which was created with new
operator. Operator delete
calls destructor and then frees memory allocated by new
.
If in C++ - like e.g. in Java - new
were the only way to create objects that the distinction between delete
and destructor would be technical. But in C++ you can create objects in other ways, the most important is - on the stack. And creating objects on the stack is recommended way. In your example
VectorClass *v_temp1 = new VectorClass(v1, size);
you are not using recommended way. You should use
VectorClass v_temp1(v1, size);
Then destructor will be automatically called at the end of the block, and there is no need (or even possibility) to use delete
.
Upvotes: 2
Reputation: 110768
A class's destructor is responsible for cleaning up any resources it might have allocated.
The delete
operator is responsible for destroying dynamically allocated objects. That is, you should delete
anything that you create with new
. The process of destroying an object of class type will first call its destructor and then deallocate the object.
So the destructor will be called whenever a class type object is destroyed. An object might be destroyed in various ways, one of which is using delete
.
We prefer automatic allocation, because it is much safer than dynamic allocation. An automatically allocated object is destroyed automatically when it goes out of scope (which will call its destructor, of course). In your case, I would instead write:
VectorClass v_temp1(v1, size);
This object does not need to be delete
d, but it certainly will be destroyed and its destructor will be called.
Upvotes: 2