Search code examples
c++classdestructordelete-operator

When to use: class destructor or delete operator


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?


Solution

  • 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 deleted, but it certainly will be destroyed and its destructor will be called.