0

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.?

CoffeeAndCream
  • 21
  • 1
  • 1
  • 5
  • What version of C++ are you working with? Or can you work with? – Nir Friedman Oct 26 '16 at 04:06
  • I'd assume C++ 11 because it wasn't specified in my class. But we can't use vectors. It's mostly about showing us fundamentals – CoffeeAndCream Oct 26 '16 at 04:07
  • What about smart pointers? The problem is: these classes want people to understand fundamentals, but they end up encouraging people to write in what's now considered really terrible style. – Nir Friedman Oct 26 '16 at 04:09
  • No, we have not learned about smart pointers. I - too - am annoyed at the styles we are forced into. I keep reading solutions to my problem but they all use vectors. I'd love to use vectors as they seem much more straight forward. Could you help me with the one problem of iterating through a loop while creating new pointer? How do you create a new pointer to an object, store it into an array of pointers, and then delete the pointer? Maybe I shouldn't be doing this. Maybe I have something fundamentally misunderstood about the assignment. Perhaps it doesn't require downcasting here. – CoffeeAndCream Oct 26 '16 at 17:57

0 Answers0