C++: Repair the assignment

This class copies correctly in one situation and badly in another. Find the missing piece.

What to build

A copy assignment operator for IntArray, so that assignment makes a deep copy.

Requirements

  • Add IntArray& operator=(const IntArray& other).
  • Make a = a; leave a unchanged.
  • Do not leak the old block, and keep the rest of the program as it is.

Input

The first line has n. The second line has the n numbers.

Output

Three lines: a, then b after its first number was set to -1, then a again after a = a;.

Constraints

1 ≤ n ≤ 100.

Example

Input:

3
1 2 3

Output:

1 2 3
-1 2 3
1 2 3

Why it works

Assignment between existing objects is a different operation from copying into a new object. Without operator=, the compiler copies the pointer, so both objects share one block and it is deleted twice.

Examples

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

Hints

Hint 1

The class has a deep copy constructor, but `b = a;` between two existing objects calls `operator=`, which you have not written.

Hint 2

`operator=` must check for self-assignment, free its old block, make a new one and copy the numbers, then return `*this`.

Solution

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

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

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

Lesson: Copying objects: shallow and deep copies →