Destructor of a class, Pupose of desctrucor, example of destructor in OOP C++

Destructor of a class, Purpose of desctrucor, example of destructor in OOP C++

In this tutorial, we will learn about the followings;

  1. What is destructor of a class in OOP C+?
  2. What is the purpose of destructor in OOP C+?
  3. Example of destructor in OOP C+

What is destructor of a class?

The destructor is a member function of the class. Destructor has the same name as the name of its class. The Tild sign ∼ is used before the name of the destructor.

  • When the object of the class destroyed, destructor also destroyed automatically.
  • One class can have only one destructor. However, one class can have many constructors.
  • Destructor overloading is impossible.

What is the purpose of the destructor of a class?

The main purpose of the destructor of a class is to free the computer memory.

Program of a destructor of a class

Serial# Code
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

 

#include<iostream>

using namespace std;

class example
{

public:

example(int n1, int n2)

{

cout<<“sum of 2 numbers is = “<<n1+n2<<endl;

}

~example()

{

cout<<“destructor completed its work to free the memory”<<endl;

}

};

int main()

{

example my_object(2,4);

}

 

A class is declared in line 3 with a name as “example”. One constructor with the same name as a class name is declared in line 6.When object “my_object” is created constructor executed and when control moves outside of the main function, then destructor is executed and free all the variables etc in computer memory. A destructor is declared in line 10.

Test Your Understandings

1.Multiple destructor for a class are possible? YES / NO

Answer - Click Here:
NO

2. Destructor for a class is represented with…………..sign?

Answer - Click Here:
∼ Tild sign

3. Destructor overloading is  very helpful to free the computer memory?

Answer - Click Here:
No, it is not possible
.