There are already many answered questions for creating an array of objects in C++ without a default constructor
how to dynamically declare an array of objects with a constructor in c++
Constructors and array of object in C++
What I want to do is to create an array that would allow me to have custom constructors for every element.
What is the best or most idiomatic way to do this in C++?
Example:
MyClass *myVar;
myVar = new MyClass[5];
int i = 0;
for(i = 0;i < num;i++)
myVar[i] = new MyClass(i,i);
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.
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 set_data method.
Example:
[stuff] //initialize array with default values
for(i = 0;i < num;i++)
myVar[i].set_data(i)
Because set_data might edit some data which should only be settable on initialisation. (Of course, a set private variable could be used to track if an object is already set, but that seems unwieldy - or is this how it's generally done in C++?)