#include <iostream>
#include <cstdint>
using namespace std;
class SensorData {
private:
uint8_t* data; // dynamic array of 8 bytes
public:
// Constructor: allocate and copy from input array
SensorData(uint8_t arr[8]) {
data = new uint8_t[8];
for (int i = 0; i < 8; i++) {
data[i] = arr[i];
}
}
// Copy constructor: deep copy
SensorData(const SensorData& other) {
data = new uint8_t[8];
for (int i = 0; i < 8; i++) {
data[i] = other.data[i];
}
}
// Destructor: free allocated memory
~SensorData() {
delete[] data;
}
void setIndex3() {
data[3] = 99;
}
void print() const {
for (int i = 0; i < 8; i++) {
cout << (int)data[i] << (i == 7 ? "" : " ");
}
cout << endl;
}
};
int main() {
uint8_t arr[8];
for (int i = 0; i < 8; i++) {
int temp;
cin >> temp;
arr[i] = static_cast<uint8_t>(temp);
}
SensorData a(arr);
SensorData b = a;
b.setIndex3();
a.print();
b.print();
return 0;
}
Explanation & Logic Summary:
new[])With a deep copy:
b does not affect aFirmware Relevance & Real-World Context:
In embedded systems, this pattern appears in:
Incorrect copy behavior can cause:
This problem reinforces:
Input
1 2 3 4 5 6 7 8
Expected Output
1 2 3 4 5 6 7 8 1 2 3 99 5 6 7 8