×
>
<

Aptitude

Constructor and Destructor in C++

Constructor and Destructor in C++

Here, in this page we will discuss about constructor and destructor in C++. The constructor is used to allocate the memory if required and constructing the object of class whereas, a destructor is used to perform required clean-up when an object is destroyed . The destructor is called automatically by the compiler when an object gets destroyed.

Constructor in C++

As the name suggest to construct space, or in direct words, Constructors are a unique class functions that do the job of initialising every object. Whenever, any object is created the constructor is called by the compiler.

  • When we create any object and don’t assign values the data of that object take up garbage values.
  • To make sure that this doesn’t happen we use constructors to assign values to them as soon as they are created or memory is assigned.
  • The new version of C though automatically calls a default constructor implicitly to assign a default value in cases when we don’t create a constructor ourselves.
  • Constructor do not have a return type

Syntax

Constructor can be declared inside the class or outside the class (using scope resolution :: operator)

Inside the class

  
class A { 
  int i; 
  public: 
     A(){ 
       // Constructor declared 
       // assignments for initialisation
}
};
  

Outside the class

  
class A
{
 int i;
 public:
     A(); 
     //Constructor declared
};

A::A()   
// Constructor definition
{
    // initialisation of values
    i=1;
}
  

  1. Constructors have the same name as class name
  2. They are called using classname and (); example A();
  3. They are initialised outside class definition and defined with class name and scope resolution :: operator.

Destructors in C++

We worked with initialising the object values, but what when the scope of the object ends, we must also destroy the object, right !. For this we use Destructors in C++. As soon as the object goes out of scope the compiler automatically destructs the object.

  1. Destructors will never have any arguments.
  2. The class name is used for the name of destructor, with a ~ sign as prefix to it.

Syntax
  
class A
{
  public:
  ~A();
};
  

Let us look at an example how we can implement destructors and constructors together in sync

  
#include
using namespace std;
class A
{
 public:
 A()
 {
  cout << "Constructor called";
 }
 ~A()
 {
  cout << "Destructor called";
 }
};
int main()
{
 A obj1; 
 // Constructor Called 
 int x=1;
 if(x)
 {
    A obj2; 
    // Constructor Called
  } 
 // Destructor Called for obj2 as obj2 out of scope
} 
// Destructor called for obj1 as obj1 out of scope
  
output
  
Constructor called
Constructor called
Destructor called
Destructor called