Thursday 23 February 2017

C++ copy constructor for class with dynamically allocated array

Just starting on C++ (a few days now), I come with C background.



I have a class that holds, mainly, an a pointer to an int array with the following code:



class Array
{

private:
int * _arr;
int _size;
public:
Array();
Array(int size);
Array(const Array& obj); // copy constructor
~Array();
void readInValues();
void mult(int num);

void add(int num);
void printArray();
};


_arr is a pointer to an int array, when creating a new instance using the copy constructor I would to create a new int array on the heap (I think). In the copy constructor:



Array::Array( const Array & obj )
{
_arr = new int[_size];


for(int i=0;i<_size;i++)
*_arr[i] = *obj._arr[i];
}


The 1st thing I do is allocate memory for the new array (_size is a primitive type so being copied automatically as far as I understood). The next thing I would like to do is copy the array itself using a loop. This parts fails the compilation saying illegal indirection. I am not sure why...

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...