What is constructor overloading in C++ – Short and Easy

Constructor overloading in C++ programming is same as function overloading. When we create more that one constructors in a class with different number of parameters or different types of parameters or different order of parameters, it is called as constructor overloading. In sample words, writing multiple constructors in a class is known as constructor overloading in C++.

We will answer constructor overloading or multiple constructor in c++ with example source code . Also, recommended to read what is constructor in C++?

For example, In below C++ source code example, we have a class called Employee containing three constructors,means, overloaded constructors as below.

  • Employee()
  • Employee(int id)
  • Employee(int id, string name)

We know that when we create an object of a class then constructor of the class gets called. So, In below C++ program, if we create objects of the class with or without arguments, then depending on arguments (shown below), the respective overloaded constructor will be called. For example, below we have created objects of the class and have shown in comment, what respective constructor is called.

  • Employee e1; //object e1 will call Employee()constructor.
  • Employee e2(123); //object e2 will call Employee(int id)constructor.
  • Employee e3(123,”John”); //object e3 will call Employee(int id, string name) constructor.

Program example of constructor overloading in C++

class Employee
{
int id;
string name;

public:
//Empty Constructor
Employee(){

this->id = 0;
this->name = "default";
}

//Overloaded constructor with int parameter
Employee(int id){

this->id = id;

}

//Overloaded constructor with a int parameter and a string
Employee(int id, string name){

this->id =id;
this->name = name;

}
void display(){

cout << "Employee Info: "<<" " << id << " " << name.c_str()<<"\n";

}
};

Here is the test C++ program that uses multiple constructors written in the class Employee. In main() program, we have created multiple class objects with arguments. Every object will call respective constructor depending upon the arguments passed in objects.

#include<iostream>>
int main(){

//Call empty constructor
Employee e1;
e1.display();

//call one parameter constructor
Employee e2(123);
e2.display();

//call two parameter constructor
Employee e3(123,"John");
e3.display();

return 0;
}

OUTPUT:

Employee Info:  0 default
Employee Info:  123
Employee Info:  123 John

NOTE:

Related Posts