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!