File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ // C++ program to demonstrate Deep Copy Constructor
2
+
3
+ // Deep Copy Constructor - Deep copy Constructor allocates separate memory for copied information. So the source and copy
4
+ // are different. Any changes made in one memory location will not affect the other location.
5
+
6
+ #include < bits/stdc++.h>
7
+ using namespace std ;
8
+
9
+ // class with a Deep Copy Constructor
10
+ class Person {
11
+
12
+ private:
13
+ char *name;
14
+
15
+ public:
16
+ // Constructor
17
+ Person (const char *iname){
18
+ name=new char [20 ];
19
+ strcpy (name,iname);
20
+ }
21
+ // Deep Copy Constructor
22
+ Person (const Person &p1){
23
+ name=new char [20 ];
24
+ strcpy (name,p1.name );
25
+ }
26
+ void concatenate (const char *str){
27
+ strcat (name,str);
28
+ }
29
+ void display (){
30
+ cout<<" Name : " <<name<<endl;
31
+ }
32
+ };
33
+
34
+ int main (){
35
+ // Creating an object of class Person (initializing it using Parameterized Constructor)
36
+ cout<<" Object 1 initialization - " <<endl;
37
+ Person p1 (" abc" );
38
+ p1.display ();
39
+ cout<<endl;
40
+
41
+ // Creating an object of class Person (initializing it using Deep Copy Constructor)
42
+ cout<<" Object 2 initialization using Deep Copy Constructor - " <<endl;
43
+ Person p2=p1;
44
+ p2.display ();
45
+ cout<<endl;
46
+
47
+ // Making some changes to original object (Object 1)
48
+ p1.concatenate (" xyz" );
49
+
50
+ cout<<" Object 1 after making changes to Object 1 - " <<endl;
51
+ p1.display ();
52
+ cout<<endl;
53
+
54
+ cout<<" Object 2 after making changes to Object 1 - " <<endl;
55
+ p2.display ();
56
+
57
+ return 0 ;
58
+ }
You can’t perform that action at this time.
0 commit comments