C++ 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
1 2 3 4 5 6 7 8 |
className{ className(return-type args){ } className(return-type args, return-type args ){ } } |
C++ Constructor Overloading Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#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:
1 2 3 4 5 6 7 8 |
id=0 dept=unknown id=101 dept=unknown dept id=102 dept=Programmer |