C++: A deep copy constructor

IntArray owns an array made with new. main copies an IntArray, changes the copy, and prints both. Without a copy constructor the two objects share one block: changing the copy changes the original, and the block is deleted twice. Write a copy constructor that makes a deep copy.

What to build

A copy constructor that gives each IntArray its own block of memory.

Requirements

  • Allocate a new block of the same size in the copy constructor.
  • Copy every number into the new block.
  • Leave the destructor deleting the block, so each block is deleted once.

Input

The first line has n (1 ≤ n ≤ 100). The second line has the n numbers.

Output

Two lines: the original numbers, then the copy's (whose first number was set to -1).

Constraints

1 ≤ n ≤ 100.

Example

Input:

3
1 2 3

Output:

1 2 3
-1 2 3

Why it works

With its own block, the copy can change without touching the original, and each destructor deletes a different block, so nothing is deleted twice.

Examples

Example 1 · Input
3
1 2 3
Expected output
1 2 3
-1 2 3
Example 2 · Input
1
42
Expected output
42
-1

Hints

Hint 1

The compiler's copy only copies the pointer, so both arrays share one block (and it is deleted twice).

Hint 2

Write IntArray(const IntArray& other): allocate a new block of other.size and copy the numbers.

Hint 3

The destructor deletes the block, so each object must own its own.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;

class IntArray {
public:
    int* data;
    int size;
    IntArray(int n) : size(n) {
        data = new int[n];
    }
    IntArray(const IntArray& other) : size(other.size) {
        data = new int[size];
        for (int i = 0; i < size; i++) data[i] = other.data[i];
    }
    ~IntArray() {
        delete[] data;
    }
    void print() const {
        for (int i = 0; i < size; i++) {
            if (i > 0) cout << " ";
            cout << data[i];
        }
        cout << endl;
    }
};

int main() {
    int n;
    cin >> n;
    IntArray a(n);
    for (int i = 0; i < n; i++) cin >> a.data[i];
    IntArray b = a;
    b.data[0] = -1;
    a.print();
    b.print();
    return 0;
}

Lesson: Copying objects: shallow and deep copies →