Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
What is a Destructor of the Class | Constructors and Destructors
C++ OOP
course content

Contenido del Curso

C++ OOP

C++ OOP

1. Fundamentals of OOP
2. Constructors and Destructors
3. Encapsulation Overview
4. Inheritance Overview
5. Polymorphism Overview

bookWhat 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.

cpp

scope

cpp

delete

cpp

termination

copy
123456
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.

cpp

ResourceHolder

cpp

FileHandler

copy
123456789101112
class ResourceHolder { public: DynamicArray(int size) { data = new int(100); } ~DynamicArray() { delete data; } private: int* data; };
1. What is the primary purpose of a destructor?
2. What is the syntax for declaring a destructor?
What is the primary purpose of a destructor?

What is the primary purpose of a destructor?

Selecciona la respuesta correcta

What is the syntax for declaring a destructor?

What is the syntax for declaring a destructor?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 7
some-alt