Object Oriented Programming - Old Questions

5. Explain about the importance of constructors and destructors with their execution sequence.

5 marks | Asked in 2075( Old Course)

Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object.

Destructor is a special class function which destroys the class object as soon as the scope of object ends. The destructor is called automatically by the compiler when the object goes out of scope.

Importance of Constructor:

  • Constructors are used to initialize the objects of the class with initial values.
  • Constructors are invoked automatically when the objects are created.
  • Constructors can have default parameters.
  • If constructor is not declared for a class , the C++ compiler generates a default constructor.
  • A constructor can be used explicitly to create new objects of its class type.
  • The constructor is executed automatically.
  • Constructor function can be overloaded.

Importance of Destructor:

  • Destructors are invoked automatically when the objects are destroyed.
  • Destructors can not have any parameter and will not return any value.
  • Destructors are declared in a program to release memory space for future utilization.

Example

#include <iostream>

using namespace std;

class MyClass

{

   private:

      int m, n;

   public:

      MyClass( )   // constructor 

      {

         m = 10;

         n = 5;

      }

      ~MyClass( )   //destructor

      {

          cout<<"Destructor called!!";

      }

      void display()

      {

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

      }

};

int main()

{

    MyClass obj;

    obj.display();

    return 0;

}