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

Course Content

C++ OOP

C++ OOP

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

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

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?

Select the correct answer

What is the syntax for declaring a destructor?

What is the syntax for declaring a destructor?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 7
We're sorry to hear that something went wrong. What happened?
some-alt