When a pointer goes out of scope, its memory is freed, so why are destructor
s created in c++?
No. You never need to explicitly call a destructor (except with placement new ). A class's destructor (whether or not you explicitly define one) automagically invokes the destructors for member objects. They are destroyed in the reverse order they appear within the declaration for the class.
When a class contains dynamic object then it is mandatory to write a destructor function to release memory before the class instance is destroyed this must be done to avoid memory leak.
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ). For example, the destructor for class String is declared: ~String() .
Destructors are invoked when you use the delete operator for objects created with the new operator.
If you're asking why C++ classes have destructors, some classes have requirements other than just freeing memory. You may have an object that's allocated a socket connection that needs to be shut down cleanly, for example.
Also, 'unscoping' a pointer does not free the memory that it points to since other pointers may be referencing it.
If you have a pointer on the stack, exiting the function will free the memory used by the pointer but not that memory pointed to by the pointer. There's a subtle but very important distinction.
When a pointer goes out of scope, the memory taken by the pointer is released. The 4 or 8 bytes (usually) of memory that are taken by the pointer, that is.
The object (or other memory) that the pointer points to is not released when the pointer goes out of scope. You do that by delete'ing the pointer. And that invokes the destructor, if there is any.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With