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

An Array of Pointers: Copies vs Addresses

hardPointers

📄 Code

Read carefully — what does this print?
1#include <iostream>
2using namespace std;
3 
4struct Item {
5 int qty;
6};
7 
8class Copies {
9 Item** m_items;
10 int m_count;
11public:
12 Copies(Item* src[], int n) : m_count(n) {
13 m_items = new Item*[n];
14 for (int i = 0; i < n; i++) {
15 m_items[i] = new Item(*src[i]);
16 }
17 }
18 ~Copies() {
19 for (int i = 0; i < m_count; i++) {
20 delete m_items[i];
21 }
22 delete[] m_items;
23 }
24 int total() const {
25 int sum = 0;
26 for (int i = 0; i < m_count; i++) {
27 sum += m_items[i]->qty;
28 }
29 return sum;
30 }
31};
32 
33class Refs {
34 Item** m_items;
35 int m_count;
36public:
37 Refs(Item* src[], int n) : m_count(n) {
38 m_items = new Item*[n];
39 for (int i = 0; i < n; i++) {
40 m_items[i] = src[i];
41 }
42 }
43 ~Refs() { delete[] m_items; }
44 int total() const {
45 int sum = 0;
46 for (int i = 0; i < m_count; i++) {
47 sum += m_items[i]->qty;
48 }
49 return sum;
50 }
51};
52 
53int main() {
54 Item a{1}, b{2}, c{3};
55 Item* list[] = {&a, &b, &c};
56 Copies copies(list, 3);
57 Refs refs(list, 3);
58 cout << copies.total() << " " << refs.total() << endl;
59 a.qty = 10;
60 c.qty = 0;
61 cout << copies.total() << " " << refs.total() << endl;
62 return 0;
63}

🎯 Your Answer