-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeepAndShallowCopy.cpp
More file actions
67 lines (58 loc) · 1.36 KB
/
Copy pathDeepAndShallowCopy.cpp
File metadata and controls
67 lines (58 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Online C++ compiler to run C++ program online
#include <iostream>
#include <cstring>
class myclass{
private:
char * data = nullptr ;
public:
// constructor to create obj at first place
myclass(const char* val) {
std::cout << "obj creating ctor" << " \n" ;
data = new char[std::strlen(val) + 1];
std::strcpy(data,val) ;
}
// shallow copy constrcutor
myclass(const myclass& other){
std::cout << "shallow ctor" << " \n" ;
data = other.data ;
}
// deep copy
myclass(const myclass& other,bool deepcopy ){
std::cout << "deep ctor" << " \n" ;
data = new char[std::strlen(other.data) + 1];
std::strcpy(data,other.data) ;
}
// Display function
void display() {
std::cout << data << std::endl;
}
// address showing func
void showaddress(){
std::cout << " address of data " << static_cast<void*>(data) <<" \n" ;
}
};
int main() {
myclass a("hello") ;
myclass b(a,1);
myclass c(a);
a.display() ;
a.showaddress() ;
c.display() ;
c.showaddress() ;
b.display();
b.showaddress() ;
return 0;
}
/*
Output :
obj creating ctor
deep ctor
shallow ctor
hello
address of data 0x396a86c0
hello
address of data 0x396a86c0
hello
address of data 0x396a86e0
=== Code Execution Successful ===
*/