Deep Copy Constructor

#include <iostream>
#include <cstdint>
#include <cstring>
using namespace std;

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

public:
    // Write your constructor here
    SensorData(uint8_t* arr){
        data=new uint8_t[8];
        memcpy(data,arr,8);
    }
    // Write your copy constructor here
    SensorData(const SensorData&o){
        data=new uint8_t[8];
        memcpy(data,o.data,8);
    }
    // Write your destructor here
    ~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;
}

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