Constructor Overloading
The program contains more than one constructor in a class with the same name, and different types of arguments are called constructor overloading.
Calling of constructor depends on the number and types of the argument passed in object.
Syntax
className{ className(return-type args){ } className(return-type args, return-type args ){ } }
#include <iostream> using namespace std; class Employee { int id; string dept; public: Employee(){ id=0; dept="unknown"; } Employee(int x){ id=x; dept="unknown dept"; } Employee(int x,string dep){ id=x; dept=dep; } void display(){ cout<<"id="<<id<<endl; cout<<"dept="<<dept<<endl; } }; int main(){ Employee emp; Employee emp1(101); Employee emp2(102,"Programmer"); emp.display(); emp1.display(); emp2.display(); return 0; }
Output:
id=0 dept=unknown id=101 dept=unknown dept id=102 dept=Programmer