I'm trying to wrap my head around C++. I'm going to just give you tiny pieces to help illustrate the idea without making things to convoluted. Btw, im only implementing these methods, i cannot change the setup or parameters.
I have a class for a dynamic array data structure that holds objects called stocks:
typedef class Stock ArrayType;
class DynamicArray {
ArrayType** items;
int numberOfElements;
...
}
Here's its constructor. I'm supposed to allocate the array and add one item, then set the number of elements.
DynamicArray::DynamicArray(ArrayType* const item){
Stock *items = NULL; // ... i guess? pointers to pointers confuse me
// now im guessing i need to create a actual stock array and point the above pointer to it
items = new Stock[1]; // ERROR: incomplete type is not allowed? I've tried several things, and cant get rid of the red squiggles
this->numberOfElements = 1;
}
Okay, there are a few problems. Off the bat, you have to include Stock first. The compiler needs the full definition of Stock
before it can compile DynamicArray
, because of memory allocation by my guess.
Secondly, you want the items
member-value to contain the reference to the array created in the constructor. So instead of defining Stock *items[1]
in the constructor, assign the value of the new
statement directly to this->items
; you can ommit this->
as long as you don't define a variable with the same name in whatever function you're working on.
Finally, you're allocating an array of pointers, so you use this syntax: new ArrayType*[1]
Additionally, just as a coding-practices point, you shouldn't mix the use of typedefs and their original types in the same source. So I'd recommend you use ArrayType
throughout or not at all.