Object Oriented Programming - Old Questions

7. What is destructor? Write a program to show the destructor call such that it prints the message "memory is released".

5 marks | Asked in 2076

Destructor is a special class function which destroys the object as soon as the scope of object ends. The destructor is called automatically by the compiler when the object goes out of scope. Destructors are declared in a program to release memory space for future utilization.

Program:

#include <iostream>

using namespace std;

class MyClass

{

   private:

      int m, n;

   public:

      MyClass( )   // constructor 

      {

         m = 10;

         n = 5;

      }

      ~MyClass( )   //destructor

      {

          cout<<"Memory is released!!";

      }

      void display()

      {

          cout<<"The sum is:"<<(m+n)<<endl;

      }

};

int main()

{

    MyClass obj;

    obj.display();

    return 0;

}

Output


When an object is created the constructor of that class is called. The object reference is destroyed when its scope ends, which is generally after the closing curly bracket } for the code block in which it is created.