My class is asking us to use static-casting in order to downcast our base pointers to derived pointers.
class Inventory_Item{
//...functions
}
class Product : public Inventory_Item {
//...functions
}
class Inventory_System {
//...functions
private:
Inventory_Item **ptr_inv_item = new Inventory_Item*[512];
item_count = 0;
}
int main(){
Inventory_Item *item;
while(!file.eof){
item = new Product();
Product *product = static_cast <Product*> (item)
//...input information into product pointer
ptr_inv_item[item_count] = product; //store into array of pointers to objects
item_count++;
}
}
I'm required to use static casting and I'm required to use pointers to objects for the ptr_inv_item array. As I iterate through the file, I'm creating new Inventory_Item base class pointers equal to derived Products. If I don't create new items each time, the array is essentially overwritten by the most recent product pointer.
So, how am I supposed to iterate through the loop and create new product objects? What I'm doing right now much be a memory leak - right? Although my program runs fine, my understanding is that in the while loop, I'm allocating memory over and over without ever deleting it. I've tried deleting each "item" at the end of my loop, but that seems to cause memory access errors (probably because now it's trying to access memory that I've since removed).
What's the best way to initialize an array of pointers to objects if those objects have to be initialized using static downcasting in a while loop? How to initialize and delete objects in a loop avoid memory leak.?