1

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++?)

1 Answer 1

6

first of all , your first example is almost correct : you need an array of POINTERS , not objects :

MyClass **myVar;
myVar = new MyClass*[5];
int i = 0;
for(i = 0;i < num;i++)
   myVar[i] = new MyClass(i,i);

first you allocate an array of pointers and you catch it with a pointer-to-pointer. then you allocate specific objects.

regarding your question, the best way is not invent the wheel at the first place! just use std::vector! for example, I want to create an array of Cars , each has different company and color:

std::vector<Car> cars;
cars.push_back(Car(Company::Toyota,Color::Red));
cars.push_back(Car(Company::Subaru,Color::Blue));

the vector first try to use move-constructor if it's implemented , and if not - copy constructor.

Sign up to request clarification or add additional context in comments.

3 Comments

Yup, don't worry about the sample code, they're more pseudocode (I'm mainly looking for the way to do this in c++, as I came from higher level languages). So vectors it is I guess!
If you're new to C++,then my advice to use STL as much as possible. vector and map are you best friends!
You can create a template class typte T. The class shall have a pointer to an array type T. Then create your own class with your own constructor. Now you can use the pointer inside your template class to point to your own class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.