CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List
C++ Code Walkthrough #53

Shallow Copy Shares the Buffer

mediumPointers

📄 Code

Read carefully — what does this print?
1#include <iostream>
2using namespace std;
3 
4class Shallow {
5public:
6 int* value;
7 Shallow(int v) { value = new int(v); }
8 // no copy constructor: the compiler copies the pointer itself
9};
10 
11class Deep {
12public:
13 int* value;
14 Deep(int v) { value = new int(v); }
15 Deep(const Deep& other) { value = new int(*other.value); }
16};
17 
18int main() {
19 Shallow s1(5);
20 Shallow s2 = s1;
21 *s2.value = 9;
22 cout << *s1.value << " " << *s2.value << endl;
23 
24 Deep d1(5);
25 Deep d2 = d1;
26 *d2.value = 9;
27 cout << *d1.value << " " << *d2.value << endl;
28 
29 cout << (s1.value == s2.value) << " " << (d1.value == d2.value) << endl;
30 return 0;
31}

🎯 Your Answer