Destructor in C++ OOP

What is destructor of a class?

  • Destructor is member function of the class.
  • Destructor have the same name as the name of its class.
  • Tild sign ∼ is used before the name of destructor.
  • When 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 constructor of a class?

  • To free the computer memory

Program:

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);

}

 

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

Test Your Understandings

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

Answer - Click Here:

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

Answer - Click Here:

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

Answer - Click Here: