yyvv yyvv - 1 month ago 14
C++ Question

How do I pass a dynamic array of objects to a parameterized constructor of another class?

I don't understand raw pointers quite well and unfortunately I'm not allowed to use

<vector>
s, so I can't figure out how to write a parameterized constructor of a class that has an array of another class objects as its property.

class A{
...
};

class B{
int size;
A *arr;
...
B(int, const A *); // am I declaring this right?
}

...

B::B(int size_, const A *arr_) { // this is the constructor I'm trying to write
size = size_;
if (arr != nullptr) delete[] arr;
arr = new A[size];
memcpy(arr, arr_, sizeof(A) * size);
}


How do I pass this argument without messing up the memory? The code above doesn't work properly, so I'd like to hear some tips. I didn't manage to google the solution although it seems like my question is already answered, I apologize in that case.

I'm not allowed to use any safe
std::
stuff. I need to figure out how to make it work using manual memory allocation from C. Oops, I mean from C++, thanks for pointing this out.

So here's the constructor that is working for me so far:

B::B(int size_, const A *arr_) {
size = size_;
arr = new A[size_];
for (int i = 0; i < size; i++) arr[i] = arr_[i];
}


Thanks for everyone's time!

Answer

In your constructor:

if (arr != nullptr) delete[] arr;

arr is a class member that's not initialized at this point. It is a garbage pointer, likely to be something other than a nullptr, and this is going to attempt to delete the garbage pointer. Obviously, this is not going to go very far.

Simply remove this. Your constructor sets size and arr, and that's all that it needs to do. There are no existing values of size and arr to worry about: you're constructing a new object.

memcpy(arr, arr_, sizeof(A) * size);

This will only work if A is a POD. Instead, use std::copy(), which will do the right thing in all cases. If you can't use std::copy() in addition not being allowed to use std::vector, then write a for-loop to copy this data, manually.