Constructors & Destructors in C++

Constructor and Destructor functions are used in a class so as to automatically perform certain operations when an object of that class type is created and destroyed.

void Stack: Stack(){
         stktop = 0;
Stack: ~ Stack();

For example, the constructor function named Stack() could be used to automatically initialize stktop = 0 when objects stack1 and stack2 are first executed. Similarly the destructor function ~Stack() may be used to automatically deallocate memory space if necessary, all without extra coding in the main function.

Parameterized Constructors in C++

Constructors are functions with the class name and are used to initialize the members of the object when it is created. Now C++ provides easier way to initialize objects using parameterized constructors. The advantage is that we could avoid more than one function calls to initialize many variables of an object.


#include <iostream>
using namespace std;

class sum{
        int a,b;
          sum(int i, int j){ a=i; b=j; }
          int get_sum(){ return (a+b); }
        sum s(2,3); //a & b initialized
        cout << s.get_sum();
        return 0;


Execution of Constructors and Destructors

Constructors are called in the order of declaration of objects and destructors aer called in the reverse order of the declaration of objects.


#include <iostream>

using namespace std;

class myclass{
                 int who;
                 myclass(int id);
}glob_ob1(1), glob_ob2(2);

myclass::myclass(int id){
         cout << "initializing " <<id<<"\n";
         who = id;
         cout << "destructing " <<who<<"\n";

       myclass local_ob1(3);
       myclass local_ob2(4);
       return 0;

initializing 1
initializing 2 
initializing 3  
initializing 4 
destructing 4  
destructing 3 
destructing 2  
destructing 1

Add a Comment

Your email address will not be published. Required fields are marked *