Constructor Overloading
Constructor can be overloaded in a similar way as function overloading.
Overloaded constructors have the same name (name of the class) but different number of arguments.
Depending upon the number and type of arguments passed, specific constructor is called.
Since, there are multiple constructors present, argument to the constructor should also be passed while creating an object.
Example 2: Constructor overloading
// Source Code to demonstrate the working of overloaded constructors
#include <iostream>
using namespace std;
class Area
{
private:
int length;
int breadth;
public:
// Constructor with no arguments
Area(): length(5), breadth(2) { }
// Constructor with two arguments
Area(int l, int b): length(l), breadth(b){ }
void GetLength()
{
cout << "Enter length and breadth respectively: ";
cin >> length >> breadth;
}
int AreaCalculation() { return length * breadth; }
void DisplayArea(int temp)
{
cout << "Area: " << temp << endl;
}
};
int main()
{
Area A1, A2(2, 1);
int temp;
cout << "Default Area when no argument is passed." << endl;
temp = A1.AreaCalculation();
A1.DisplayArea(temp);
cout << "Area when (2,1) is passed as argument." << endl;
temp = A2.AreaCalculation();
A2.DisplayArea(temp);
return 0;
}
For object A1, no argument is passed while creating the object.
Thus, the constructor with no argument is invoked which initialises length to 5 and breadth to 2. Hence, area of the object A1 will be 10.
For object A2, 2 and 1 are passed as arguments while creating the object.
Thus, the constructor with two arguments is invoked which initialises length to l (2 in this case) and breadth to b (1 in this case). Hence, area of the object A2 will be 2.
Output
Default Area when no argument is passed. Area: 10 Area when (2,1) is passed as argument. Area: 2