Multiple constructors in a class means a class can contain more than one constructor. This is also known as constructor overloading. All constructors are defined with the same name as the class they belong to. All the constructors contain different number of arguments. Depending upon the number of arguments, the compiler executes appropriate constructor.
Multiple constructors can be declared in different ways:
integer(); // Default Constructor(No arguments)
integer(int, int); // Parameterized Constructor(Two arguments)
When an object is created the first constructor is invoked. In the first case, the constructor itself supplies the data values and no values are passed by the calling program. In the second case, the function call passes the appropriate values from main( ) to the constructor.
Example:
#include<iostream.h>
#include<conio.h>
class integer
{
int m, n;
public:
integer()
{
m = 0; n = 0;
}// constructor 1 default constructor
integer(int a, int b)
{
m = a;
n = b;
cout<<"value of m="<<a;
cout<<"value of n="<<b;
} // constructor 2 parameterized constructor
};
void main()
{
clrscr();
integer i1; //calls constructor 1
integer i2(20,40); // calls constructor2
getch();
}
In the above example, constructor is overloaded by defining two constructors in the same class. Both the definitions are different with respect to number of arguments. The first constructor does not accept any argument and the second constructor accepts two integer arguments.