Skip to content

Commit a8305ec

Browse files
authored
Merge pull request #833 from pushpakumari5117/issue-831
Added the code for Constructor Overloading
2 parents 49989ff + 224b265 commit a8305ec

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// C++ program to demonstrate Constructor Overloading
2+
3+
// Constructor Overloading - It is defined as the concept of having more than one
4+
// constructors with different parameters in a class.
5+
6+
#include<bits/stdc++.h>
7+
using namespace std;
8+
9+
// class with four Constructors (each with different parameters)
10+
class Person{
11+
private:
12+
string name;
13+
int age;
14+
public:
15+
Person(){
16+
cout<<"Default Constructor"<<endl;
17+
name="no_name";
18+
age=0;
19+
}
20+
Person(string iname){
21+
cout<<"Constructor with name as parameter"<<endl;
22+
name=iname;
23+
age=0;
24+
}
25+
Person(int iage){
26+
cout<<"Constructor with age as parameter"<<endl;
27+
age=iage;
28+
name="no_name";
29+
}
30+
Person(string iname,int iage){
31+
cout<<"Constructor with name and age as parameter"<<endl;
32+
name=iname;
33+
age=iage;
34+
}
35+
void display(){
36+
cout<<"Name : "<<name<<endl;
37+
cout<<"Age : "<<age<<endl;
38+
}
39+
};
40+
41+
int main(){
42+
// Creating an object of class Person (giving no parameter)
43+
Person p1;
44+
p1.display();
45+
cout<<endl;
46+
47+
// Creating an object of class Person (giving name as parameter)
48+
Person p2("abc");
49+
p2.display();
50+
cout<<endl;
51+
52+
// Creating an object of class Person (giving age as parameter)
53+
Person p3(10);
54+
p3.display();
55+
cout<<endl;
56+
57+
// Creating an object of class Person (giving name and age as parameter)
58+
Person p4("abc",10);
59+
p4.display();
60+
61+
return 0;
62+
}

0 commit comments

Comments
 (0)