Conteúdo do Curso
C++ OOP
C++ OOP
What is a Destructor of the Class
Syntax of Destructor
Even though they serve opposite purposes creating a destructor is very similar to creating a constructor. They share almost the same declaration principles. The general approach to creating one is:
- Name: It has the same name as the class, but is preceded by a tilde (~).
- No Return Type: It does not have a return type, not even void.
- No Parameters: It cannot take any parameters.
- Automatic Invocation: It is called automatically by the compiler when the object goes out of scope or is explicitly deleted.
Automatic Invocation of Destructors
The automatic invocation of destructors refers to the automatic calling of the destructor. This ensures that resources held by the object are properly released, thus helping to prevent memory leaks and resource leaks.
scope
delete
termination
int main() { { Example obj; // Object created } // Object goes out of scope here, destructor is invoked }
- When an object goes out of scope.
- When the delete operator is used to delete dynamically allocated objects.
- When the program terminates.
The Need of Destructors
The primary purpose of a destructor is to release resources acquired by the object during its lifetime. This includes closing file handles, deallocating memory (using new) or simmilar tasks.
ResourceHolder
FileHandler
class ResourceHolder { public: DynamicArray(int size) { data = new int(100); } ~DynamicArray() { delete data; } private: int* data; };
Obrigado pelo seu feedback!