Constructor
overloading in C++
Prepared By: Vandna Bansla
Constructor overloading
• Constructors can be overloaded in a similar way as
function overloading.
• Overloaded constructors have the same name (name of the class) but
the different number of arguments. Depending upon the number and
type of arguments passed, the corresponding constructor is called.
Example 1: Constructor overloading
#include <iostream>
using namespace std; int main() {
class Person { Person person1, person2(45);
private: cout << "Person1 Age = " << [Link]() << endl;
int age; cout << "Person2 Age = " << [Link]() << endl;
public:
return 0;
Person() { }
age = 20;
}
Person(int a) { Output
age = a;
} Person1 Age = 20
int getAge() { Person2 Age = 45
return age;
}
};
In this program, we have created a class Person that has a single
variable age.
We have also defined two constructors Person() and Person(int a):
• When the object person1 is created, the first constructor is called
because we have not passed any argument. This constructor initializes
age to 20.
• When person2 is created, the second constructor is called since we
have passed 45 as an argument. This constructor initializes age to 45.
Example 2: Constructor overloading
#include <iostream> double calculateArea() {
using namespace std; return length * breadth;
}
class Room {
};
private:
int main() {
double length; Room room1, room2(8.2, 6.6), room3(8.2);
double breadth;
public: cout << "When no argument is passed: " << endl;
Room() { cout << "Area of room = " << [Link]() << endl;
length = 6.9;
breadth = 4.2; cout << "\nWhen (8.2, 6.6) is passed." << endl;
cout << "Area of room = " << [Link]() << endl;
}
Room(double l, double b) {
cout << "\nWhen breadth is fixed to 7.2 and (8.2) is passed:" << endl;
length = l; cout << "Area of room = " << [Link]() << endl;
breadth = b;
} return 0;
Room(double len) { }
length = len;
breadth = 7.2;
}
Output
When no argument is passed:
Area of room = 28.98
When (8.2, 6.6) is passed.
Area of room = 54.12
When breadth is fixed to 7.2 and (8.2) is passed:
Area of room = 59.04
• When room1 is created, the first constructor is called. length is initialized to
6.9 and breadth is initialized to 4.2.
• When room2 is created, the second constructor is called. We have passed
the arguments 8.2 and 6.6. length is initialized to the first argument 8.2 and
breadth is initialized to 6.6.
• When room3 is created, the third constructor is called. We have passed one
argument 8.2. length is initialized to the argument 8.2. breadth is initialized
to the 7.2 by default.