Deep Copy Constructor

#include <iostream>
#include <cstdint>
#include <algorithm> // for std::copy

using namespace std;

class SensorData {
private:
    uint8_t* data;  // dynamically allocated buffer of size 8

public:
    // 1. Constructor: Allocates memory and copies initial data
    SensorData(const uint8_t arr[8]) {
        data = new uint8_t[8];
        for (int i = 0; i < 8; i++) {
            data[i] = arr[i];
        }
    }

    // 2. Deep Copy Constructor: Ensures independent memory for the new object
    SensorData(const SensorData& other) {
        // Allocate new memory on the heap
        data = new uint8_t[8];
        // Copy the actual values from the 'other' object
        for (int i = 0; i < 8; i++) {
            data[i] = other.data[i];
        }
    }

    // 3. Destructor: Clean up the heap memory
    ~SensorData() {
        delete[] data;
    }

    void setIndex3() {
        if (data) data[3] = 99;
    }

    void print() const {
        for (int i = 0; i < 8; i++) {
            // Cast to int for readable numeric output
            cout << (int)data[i] << (i == 7 ? "" : " ");
        }
        cout << endl;
    }
};

int main() {
    uint8_t arr[8];
    for (int i = 0; i < 8; i++) {
        int temp;
        if (!(cin >> temp)) break;
        arr[i] = static_cast<uint8_t>(temp);
    }

    // Construct object 'a'
    SensorData a(arr);
    
    // Copy object 'a' into object 'b' (Triggers Copy Constructor)
    SensorData b = a;

    // Modify only 'b'
    b.setIndex3();

    // Print results: 'a' should be unchanged, 'b' should have 99 at index 3
    a.print();
    b.print();

    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

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