Explain Constructor and Deconstructor in C++?

Constructor is a special method that is invoked automatically at the time of object creation and used to initialize the data members of a new object generally.

There can be two types of constructors in C++.

  • Default constructor
  • Parameterized constructor

Example-

class Employee  
 {  
   public:  
        Employee()    
        {    
            cout<<"Default Constructor Invoked"<<endl;    
        }    
};  
int main(void)   
{  
    Employee e1; //creating an object of Employee   
    Employee e2;   
    return 0;  
}

Copy Constructor

A Copy constructor is an overloaded constructor used to declare and initialize an object from another object. It is useful when we initialize the object with another existing object of the same class type. For example, Student s1 = s2, where Student is the class.

class A  
{  
   public:  
    int x;  
    A(int a)                // parameterized constructor.  
    {  
      x=a;  
    }  
    A(A &i)               // copy constructor  
    {  
        x = i.x;  
    }  
};  
int main()  
{  
 A a1(20);              
 A a2(a1);               
 cout<<a2.x;  
  return 0;  
}

Destructors
A destructor works opposite to constructor; it destructs the objects of classes. It can be defined only once in a class. Like constructors, it is invoked automatically and prefixed with a tilde sign (~).

Example-

class Employee  
 {  
   public:  
        Employee()    
        {    
            cout<<"Constructor Invoked"<<endl;    
        }    
        ~Employee()    
        {    
            cout<<"Destructor Invoked"<<endl;    
        }  
};  
int main(void)   
{  
    Employee e1; //creating an object of Employee   
    Employee e2; //creating an object of Employee  
    return 0;  
}