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

Three Files: An Aggregation That Shows Later Changes

hardModular Programming

📄 Code

Read carefully — what does this print?
1// ===== Part.h =====
2#ifndef PART_H
3#define PART_H
4#include <iostream>
5 
6class Part {
7 int m_id;
8 int m_qty;
9public:
10 Part(int id, int qty) : m_id(id), m_qty(qty) {}
11 void setQty(int qty) { m_qty = qty; }
12 friend std::ostream& operator<<(std::ostream& os, const Part& p) {
13 return os << "#" << p.m_id << " x" << p.m_qty;
14 }
15};
16 
17#endif
18 
19// ===== Kit.h =====
20#ifndef KIT_H
21#define KIT_H
22#include <iostream>
23#include "Part.h"
24 
25class Kit {
26 const Part* m_parts[4];
27 int m_count = 0;
28public:
29 Kit& operator+=(const Part& part) {
30 for (int i = 0; i < m_count; i++) {
31 if (m_parts[i] == &part) {
32 return *this;
33 }
34 }
35 m_parts[m_count] = &part;
36 m_count++;
37 return *this;
38 }
39 friend std::ostream& operator<<(std::ostream& os, const Kit& kit) {
40 static int printed = 0;
41 printed++;
42 os << "Kit " << printed << " (" << kit.m_count << ")" << std::endl;
43 for (int i = 0; i < kit.m_count; i++) {
44 os << " " << *kit.m_parts[i] << std::endl;
45 }
46 return os;
47 }
48};
49 
50#endif
51 
52// ===== main.cpp =====
53#include <iostream>
54#include "Kit.h"
55using namespace std;
56 
57int main() {
58 Part bolt(1, 10), nut(2, 20);
59 Part bolt2(1, 10);
60 Kit kit;
61 kit += bolt;
62 kit += nut;
63 kit += bolt;
64 kit += bolt2;
65 cout << kit;
66 bolt.setQty(99);
67 cout << kit;
68 return 0;
69}

🎯 Your Answer

← Previous