< C++ Tutorial

C++ constructors and destructors

← Previous Next →


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.

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

Properties of Constructor

  •  Constructor name  must be same as the name of the class
  • Contructors never have return type.

Constructors can be defined either inside the class definition or outside class definition using class name and scope resolution :: operator.

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

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

Types of Constructors

Constructors are of three types :

  • Default Constructor
  • Parametrized Constructor
  • Copy COnstructor

Default Constructor

Default constructor is the constructor which doesn't take any argument. It has no parameter.

Syntax :

class_name () 
{ 
  //Constructor Definition 
}

Example :

class Cube
{
    int side;
    public:
    
    Cube() 
    {  
      side=10;
    }
};

int main()
{
    Cube c;
    cout << c.side;
}

Parameterized Constructor

These are the constructors with parameter. Using this Constructor you can provide different values to data members of different objects, by passing the appropriate values as argument.

Example :

class Cube
{
    int side;
    public:
    
    Cube(int x)
    {  
        side=x;
    }
};

int main()
{
    Cube c1(10);
    Cube c2(20);
    Cube c3(30);
    cout << c1.side;
    cout << c2.side;
    cout << c3.side;
}

Copy Constructor

These are special type of Constructors which takes an object as argument, and is used to copy values of data members of one object into other object. We will study copy constructors in detail later.


Destructors

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.

The syntax for destructor is same as that for the constructor, the class name is used for the name of destructor, with a tilde ~ sign as prefix to it.

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

Destructors will never have any arguments.

← Previous Next →