title: Array/Vector of Objects with custom constructors for elements
body: <p>There are already many answered questions for creating an array of objects in C++ without a default constructor</p>
  
  <p><a href="https://stackoverflow.com/questions/8462895/how-to-dynamically-declare-an-array-of-objects-with-a-constructor-in-c">how to dynamically declare an array of objects with a constructor in c++</a></p>
  
  <p><a href="https://stackoverflow.com/questions/8312054/constructors-and-array-of-object-in-c">Constructors and array of object in C++</a></p>
  
  <p>What I want to do is to create an array that would allow me to have custom constructors for every element.</p>
  
  <p><strong>What is the best or most idiomatic way to do this in C++?</strong></p>
  
  <p>Example:</p>
  
  <pre><code>MyClass *myVar;
  myVar = new MyClass[5];
  int i = 0;
  for(i = 0;i &lt; num;i++)
     myVar[i] = new MyClass(i,i);
  </code></pre>
  
  <p>In this case, you see an array of pointers and in the for loop we create an object with custom constructor parameters. However, I'm not sure if this is the best way, as it allocates the data on the heap, might not be consecutive, allocation issues, adds a pointer, etc.</p>
  
  <p>My reason for asking this is that I do not want to initialize an array of n objects _only to edit the elements with a <code>set_data</code> method.</p>
  
  <p>Example:</p>
  
  <pre><code>[stuff] //initialize array with default values
  for(i = 0;i &lt; num;i++)
     myVar[i].set_data(i)
  </code></pre>
  
  <p>Because <code>set_data</code> might edit some data which should only be settable on initialisation. (Of course, a <code>set</code> private variable could be used to track if an object is already set, but that seems unwieldy - <em>or is this how it's generally done in C++?</em>)</p>