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

Copy or Address?

mediumPointers

📄 Code

Read carefully — what does this print?
1#include <iostream>
2using namespace std;
3 
4struct Box {
5 int weight;
6};
7 
8class Crate {
9 Box* m_box;
10public:
11 Crate(const Box& box) { m_box = new Box(box); }
12 ~Crate() { delete m_box; }
13 int weight() const { return m_box->weight; }
14};
15 
16class Manifest {
17 const Box* m_box;
18public:
19 Manifest(const Box& box) { m_box = &box; }
20 int weight() const { return m_box->weight; }
21};
22 
23int main() {
24 Box parcel{10};
25 Crate crate(parcel);
26 Manifest manifest(parcel);
27 parcel.weight = 25;
28 cout << crate.weight() << " " << manifest.weight() << endl;
29 
30 Box other{40};
31 Manifest second(other);
32 other.weight += 2;
33 cout << second.weight() << " " << crate.weight() << endl;
34 return 0;
35}

🎯 Your Answer