Hi
I have a homework problem I would need a hint for.
I need to create an array of objects using dynamic memory allocation. The objects use a constructor that takes a parameter that decides how big another array, inside the object, should be. The array inside the object is also created with dynamic memory allocation.
What i would like to work is something like this
Object * array = new Object[arraySize](objectsArraySize);
but that obviously doesn't work. The objectsArraySize is the same for all the elements in the array.
Since the objectsArraySize needs to be set during initialization of the objects, I can't just make a loop after the array is created, populating it with the objectsArraySize.
Could anyone give me a push in the right direction?
Objects allocated with new[] must be default constructable.
You can make a static class member and give it a value before calling new[] and use it in the default constructor as it would be if passed to the constructor with parameter
I assume when you defined your list that you did not #include <list>?
And I believe the OP wants to know how to construct an array of dynamically allocated objects, so I don't think your example is quite correct.
Thanks
I'm trying to work around the issue by making the constructor of the class take no parameters, and making a member function that creates the array using dynamic memory allocation. Is it possible to this, allocationg new memory inside a created object?
I'm getting no compile-time errors, but when i use the member function i get "Invalid memory size"-error...
The member function looks like this:
Depends.
Let's say that, in your class, you have a pointer that you intend to use to point to the dynamically allocated memory. If that pointer was public you could set the dynamic memory to it in main. If it was private you could still do so by creating a function.
For example, in your example, I presume jumps is a double*. In that case it should work.
Note that your value in subscripts, nrofJumps, is different by one letter from fNrofJumps. That may be the source of your error; using an undefined variable as your array size. (Or maybe you initialized it to zero in your default constructor. Who knows.) Also keep in mind that if you passed this function a negative number you would get an error, so be sure to implement a check for that.