Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are destructors required in C++?

Tags:

c++

When a pointer goes out of scope, its memory is freed, so why are destructors created in c++?

like image 430
Access Denied Avatar asked Dec 13 '08 11:12

Access Denied


People also ask

Are destructors mandatory?

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.

In which case destructor is mandatory?

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.

What is destructor What is the importance of destructor?

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() .

Why are destructors used and which operator is used with it?

Destructors are invoked when you use the delete operator for objects created with the new operator.


2 Answers

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.

like image 156
paxdiablo Avatar answered Nov 15 '22 21:11

paxdiablo


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.

like image 35
NeARAZ Avatar answered Nov 15 '22 22:11

NeARAZ