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