- In our previous article of “Function Overloading”, we had discussed how a function can be overloaded.
- In this article, we will focus on Constructor Overloading.
- Similar to other normal function, we can also overload the constructor.
- Consider the following class ‘Rectangle’ in which we are using multiple constructors (Overloading Constructor)
class Rectangle
{
int length;
int width;
public :
Rectangle( ) ; // default constructor
Rectangle(int, int); // Parameterized constructor
Rectangle(Rectangle &); // Copy constructor
};
Rectangle :: Rectangle( )
{
length = 0;
width = 0;
}
Rectangle :: Rectangle(int l, int w)
{
length = l;
width = w;
}
Rectangle :: Rectangle(Rectangle &o)
{
length = o.length;
width = o.width;
}
// driver function
void main( )
{
Rectangle r1; // Calls default constructor
Rectangle r2(20, 30); // Call parameterized constructor
Rectangle r3 = r2; // Calls copy constructor
getch();
}
- In above example we are using three different constructor functions in class Rectangle.
- First constructor is default constructor and has no argument.
- Second constructor is parameterized constructor and has two arguments of integer type.
- Third constructor is the copy constructor and it uses the reference of same class object as argument.
- Also as shown in the main function we can call first constructor by simply creating object.
Rectangle r1;
- We can call second constructor by passing argument during object creation.
Rectangle r2(20, 30);
- We can call third constructor by copy initialization method. Also we can call by passing argument of object of type rectangle.
Rectangle r3 = r2;
- So as we ca see that we can also define multiple constructors for creating objects in different manner based on our requirement.
- When we need empty object to be created, we simply call default constructor.
- Similarly, if we need to create an object populated with some initial data, we can call parameterized constructor for the same.
- This way, constructor overloading allows us to define multiple constructors with initialize objects differently based on our choice.