Constructor Overloading / Multiple Constructor


It is also possible to define more then one constructors in the same class. The process of declaring more then one constructors in the same class is known as constructor overloading.

Example:
#include<iostream.h>
#include<conio.h>
class Rectangle
{
int Height, Width;
public:
Rectangle (); // Default Constructor
Rectangle (int h, int w); // Parameterized Constructor
Rectangle (Rectangle &r); // Copy Constructor

void Display(void)
{
cout<< "Height="<<Height<<"Width="<<Width<<endl;
}
};
Rectangle :: Rectangle ()
{
Height = 0;
Width = 0;
}
Rectangle :: Rectangle (int h, int w)
{
Height = h;
Width = w;
}
Rectangle:: Rectangle (Rectangle &r)
{
Height = r. Height;
Width = r. Width;
}
int main(void)
{
clrscr();
Rectangle R1;
R1. Display ();
Rectangle R2 (21, 42);
R2. Display ();
Rectangle R3 (R2);
R3. Display ();
getch ();
return (0);
}
Output:
Height=0 Width=0
Height =21 Width =42
Height =21 Width =42

     

Here the class Rectangle contains three constructors.
The statement Rectangle R1 invokes the default constructor and initializes Height and Width to 0.
The statement Rectangle R2 (21, 42) invokes the parameterized constructor and initialize Height to 21 and Width to 42.
The statement Rectangle R3 (R2) invokes the copy constructor and copy the value of data member of object R2 into object R3.

Download Projects


Download Programs