title: Initialize an array of pointers to objects using static downcasting?
body: <p>My class is asking us to use static-casting in order to downcast our base pointers to derived pointers. </p>
  
  <pre><code>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 &lt;Product*&gt; (item)
          //...input information into product pointer
  
          ptr_inv_item[item_count] = product; //store into array of pointers to objects
          item_count++;
      }
   }
  </code></pre>
  
  <p>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 <em>don't</em> create new items each time, the array is essentially overwritten by the most recent product pointer. </p>
  
  <p>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 <em>now</em> it's trying to access memory that I've since removed). </p>
  
  <p>What's the best way to initialize an array of pointers to objects <em>if</em> 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.?</p>