title: How to fill an array of object pointers in C++?
body: <p>I am trying to complete a homework assignment to create a Shape class hierarchy. In main(), I am trying to fill an array of pointers to the Shape objects. Then, after filling I need to loop through that array and call the print() (here called "SendToString") function on each object pointer.</p>
  
  <p>When running this it crashes on the 2nd for loop at runtime right after I enter some shapes and then enter 'done'. It can't seem to loop through the shape_array?</p>
  
  <p>In getShape(), if the user types 'done' in the console, a NULL pointer is returned. When a NULL pointer is returned from getShape(), the loop in main() should exit and stop filling the array.</p>
  
  <p>What is wrong with my code? I have combed through for hours and cannot see the problem. Thanks.</p>
  
  <pre><code>#include "stdafx.h"
  #include &lt;iostream&gt;
  #include "Shape.h"
  #include &lt;string&gt;
  
  using namespace std;
  
  Shape* getShape();
  
  int main()
  {
  
      int i; //fill the shape array.
      int j; //loop through the shape array.
      string output;
  
      Shape* shape_array[15]; //array of base Shape pointers
      Shape *shape_ptr;
  
      int nElements = sizeof(shape_array) / sizeof(shape_array[0]);
  
      cout &lt;&lt; "Enter a list of shapes - 'done' to end" &lt;&lt; endl;
  
      //fill the array of shape object pointers
      for (i =0; i &lt;= nElements; i++) { //loop through the defined array of 15 elements
  
          shape_ptr = getShape(); //return a shape ptr or NULL ptr
          if (shape_ptr== NULL) 
          {
              break; //stop filling the array (stop calling getShape)
          }
          else
          {
              shape_array[i]= shape_ptr; //add the shape pointer
  
          }
  
      } //end for
      cout &lt;&lt; "The list of shapes entered..." &lt;&lt; endl;
  
      for (j = 0; j &lt; nElements; j++) {
  
          output = shape_array[j]-&gt;SendToString();
          cout &lt;&lt; output &lt;&lt; endl;
      } 
  
      return 0;
  
  } //end main
  </code></pre>
  
  <p>And here is the Output: </p>
  
  <pre><code>Enter a list of shapes - 'done' to end
  
  Enter the shape's color (or 'done')...
  green
  Enter shape type...
  circle
  Enter the radius...
  5.0
  Enter the shape's color (or 'done')...
  red
  Enter shape type...
  circle
  Enter the radius...
  4.0
  Enter the shape's color (or 'done')...
  done
  User entered done!
  The list of shapes entered...
  green circle with a radius of 5 and area of 78
  </code></pre>
  
  <p>It cannot print the second object and crashes there.</p>