Skip to content

Commit 86a2f60

Browse files
authored
Merge pull request #847 from pushpakumari5117/issue-845
Added the code for Shallow Copy Constructor in C++
2 parents 9edd63f + 758c6e4 commit 86a2f60

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// C++ program to demonstrate Shallow Copy Constructor
2+
3+
// Shallow Copy Constructor - Shallow Copy Constructor copies references to original objects.
4+
// The compiler provides a default copy constructor. Since, both objects refer to the same memory location,
5+
// the change made to one object will be reflected to the other object as well.
6+
7+
#include<bits/stdc++.h>
8+
using namespace std;
9+
10+
class Person{
11+
12+
private:
13+
char *name;
14+
15+
public:
16+
// Parameterized Constructor
17+
Person(const char *iname){
18+
name=new char[20];
19+
strcpy(name,iname);
20+
}
21+
void concatenate(const char *str){
22+
strcat(name,str);
23+
}
24+
void display(){
25+
cout<<"Name : "<<name<<endl;
26+
}
27+
};
28+
29+
int main(){
30+
// Creating an object of class Person (initializing it using Parameterized Constructor)
31+
cout<<"Object 1 initialization - "<<endl;
32+
Person p1("abc");
33+
p1.display();
34+
cout<<endl;
35+
36+
// Creating an object of class Person (initializing it using Shallow Copy Constructor)
37+
cout<<"Object 2 initialization using Shallow Copy Constructor - "<<endl;
38+
Person p2=p1;
39+
p2.display();
40+
cout<<endl;
41+
42+
// Making some changes to original object (Object 1)
43+
p1.concatenate("xyz");
44+
45+
cout<<"Object 1 after making changes to Object 1 - "<<endl;
46+
p1.display();
47+
cout<<endl;
48+
49+
cout<<"Object 2 after making changes to Object 1 - "<<endl;
50+
p2.display();
51+
52+
return 0;
53+
}

0 commit comments

Comments
 (0)