assignment operator with pointers c 2b 2b

Solutions on MaxInterview for assignment operator with pointers c 2b 2b by the best coders in the world

showing results for - "assignment operator with pointers c 2b 2b"
Manuel
02 Jun 2019
1class Array
2{
3public:
4    Array(int N)
5    {
6         size = N;
7         arr = new int[N];
8    }
9
10    //destructor
11    ~Array()
12    {
13        delete[] arr;
14    }
15
16    //copy constructor
17    Array(const Array& arr2)
18    {
19        size = arr2.size;
20        arr = new int[size];
21        std::memcpy(arr, arr2.arr, size);
22    }
23
24    //overload = operator
25    Array& operator=(const Array& arr2) 
26    {
27        if (this == &arr2)
28            return *this; //self assignment
29        if (arr != NULL)
30            delete[] arr; //clean up already allocated memory
31
32        size = arr2.size;
33        arr = new int[size];
34        std::memcpy(arr, arr2.arr, size);
35        return *this;
36    }
37
38private:
39    int size;    //array elements
40    int *arr;    //dynamic array pointer
41};