• A class is defined with the goal of creating user defined data type, which is similar to build-in-data-type.
  • Built-in data type variables can be initialized at the time of declaration but we cannot initialize the class object during declaration such as shown below:
int   a = 20;              // Simple built-in-data-type variable. Allow
student s = 30;            // Not allowed. Student is a class object
  • To initialize a class object during creation, we use special member function known as constructor.
  • The name of the constructor is same as your class name.
  • Constructor is called automatically whenever we create an object.
  • It is known as constructor because it constructs the value of the variable inside the class.
  • Constructor has the following characteristics:
  1. It should be declared in public section
  2. It is called whenever object is created.
  3. It does not have any return type, not even void
  4. It cannot be inherited but child class can call parent class constructor.
  5. Constructors cannot be virtual
  6. We cannot refer to its address.
  7. An object with a constructor cannot be used as a member of union.
  • Constructors can be categorized into the following types:
  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
  4. Do-nothing Constructor
  5. Dynamic Constructor

Default Constructor

  • A constructor that accepts no argument (parameter) is known as default constructor.
  • default constructor is useful when we want to initialize class objects with some initial or default value.
  •  Consider the following class ‘Box’ in which we are initializing member of class ‘height’ and ‘width’ at the time of creating object.
/* Program to demonstrate the use of constructor. */
#include "iostream.h"
 
class  Box
{
    double height;
    double width;
    public :
           Box();        // Constructor declaration.
           void show();   // display content of box.
};
// Definition of constructor function
Box:: Box()
{
    height  = width = 0.0;
}
void Box :: show()
{
   cout << "Box Height is "<<height <<" and width is "<<width <<endl;
}

void main( )
{
    Box b1;     // Automatically initialize the value of height and width
    b1.show();
}
  • In above class we have defined constructor ‘Box’.
  • We are passing no argument into the constructor.
  • In the constructor definition we initialize height and width equal to zero.
  • Constructor is automatically called when we create an object.
  • In above example our constructor ‘Box’ has no argument so it is the default constructor.
  • Note that default constructor initializes each and every class object with the same initial or default value.

Parameterized Constructor

  • Default constructor is only helpful if we want to initialize all the objects with some fixed values.
  • But sometimes it is necessary to initialize all object variables with different values and it is more practical also.
  • To achieve this, have to use parameterized constructor.
  • A constructor that accepts argument is called parameterized constructor.”
  • Consider the following code snippet of class ‘Box’ in which we are initializing member of class ‘height’ and ‘width’ with different value for each object.
class  Box
{
    double height;
    double width;
    public :
           Box();        // default Constructor.
           Box(double, double) ;  // parameterized constructor.
};
// Definition of default constructor.
Box:: Box()
{
    height  = width = 0.0;
}
 // Definition of parameterized constructor.
Box :: Box(double h, double w)
{
    height = h ;
    width = w ;
}
  • We can pass argument to the constructor while creating object by two ways:
  1. By calling the constructor explicitly:
Box b1 = Box(20.0, 30.0);
  • Here we are passing 20.0 and 30.0 which will be received as ‘h’ and ‘w’ in the parameterized constructor.
  1. By calling constructor implicitly:
  • This method is also known as shortcut method. It is easy to write and read.
Box b1(20.0, 30.0);
  • The main function for the above class can be written as follow:
void main( )
{
    Box b1;     // will call default constructor.
    b1.show();  // height and width will be initialized by 0.0

    Box b2 = Box(20.0, 30.0) ; // Explicit call
    Box b3(25.0, 35.0) ;       // Implicit call 

    b2.show() ;
    b3.show() ; 
}

Copy Constructor

  • We can pass any variable (either primary data type, array, structure or class object) as argument in function but we cannot pass the same class object as argument.
  • But we can pass the reference of the same class object as argument.
  • This is known as copy constructor.

“In constructor when reference of the same class object is passed as argument then it is called copy constructor.”

  • Consider the following class ‘Box’ in which height and width members of class are initialized by passing reference of class ‘Box’.
class   Box
{
    double height;
    double width;
    public :
           Box(Box &);    // Copy constructor
};

Box :: Box(Box &o)   // Definition of Copy constructor.
{
   height = o.height ;
   width  = o.width ;
}
  • We can initialize copy constructor by three ways:
  1. By calling the constructor explicitly:
Box b2  = Box(b1);

  1. By calling constructor implicitly:
  • This method is also known as shortcut method. It is easy to write and read.
Box b2(b1);
  1. Copy Initialization:
  • The way of initialization of object using copy constructor in the form of:
classname object1 = object2
  • It is known as “copy initialization”.
Box b2 = b1;                  // Copy initialization
Do-nothing Constructor
  • When no constructor have defined by the programmer in class, C++ compiler automatically calls its own constructor during object creation.
  • This constructor is known as implicit constructor
  • But when we have used any constructor in our class, this implicit constructor will not work so it will create problem in following case:
class Box
{
    double height, width;
    public :
    Box (double, double) ;    // Parameterized constructor
};

Box :: Box(double h, double w)
{
    height = h ;
    width = w ;
}

// main function
void main( )
{
   Box b1;                   // Call default constructor
   Box b2(20.0, 30.0);       // Call parameterized constructor
}
  • In above program we have used only one parameterized constructor so it will be called only when we are passing argument during object declaration.
  • Also we have defined our own constructor so implicit constructor will not be called.
  • So during creating object ‘r1’ neither implicit constructor nor parameterized constructor will be called so we are getting compilation error.
  • To remove this compilation error we have to supply do-nothing constructor, which does nothing, and also it has no any argument. (That means it is default constructor).
  • So in above program we have to use do-nothing constructor as follow:
Box :: Box ( ) { }    // Do-nothing constructor

Dynamic Constructor

  • Dynamic constructor is used for dynamic memory allocation of the object.
  • We allocate  memory by using ‘new’ operator in the constructor function.
  • Consider the following example in which we are creating the two-dimensional matrix using dynamic memory allocation.
/* Program to demonstrate the use of dynamic constructor */

#include "iostream.h"

class matrix
{
   int **m;
   int r,c;
   public :
          matrix()          // Default constructor
          {
             int i,j;
             cout << "Enter the size of the row and column of matrix : ";
             cin >> r >> c;

             // Dynamically allocate the memory
             m=new int*[r];       // Allocate the memory for the 'r' row
            
            for(i=0;i<r;i++)
                 m[i]=new int[c];           // Allocate the memory for the 'c' column
           // Read the value
           cout << "Enter the elements of the matrix\n";
           for( i = 0 ; i < r ; i++ )
           {
              for( j = 0 ; j < c ; j++)
              {
                 cin >> m[i][j];
              }
           }
       }
};

void main() 
{
    matrix mat;          // Call constructor function
}
  • Besides this, we can also define multiple constructors to initialize objects differently by overloding constructor. Fore more details on how to overload constructor, please read our article, “Constructor Overloading”.
  • Also read about Destructor.