File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments