how to dynamically declare an array of objects with a constructor in c++

MyClass *myVar;
myVar = new MyClass[num];

Actually in this form you cannot invoke constructor which takes parameter(s). It is not allowed by the language specification.

However, if you use std::vector, which I recommend you to use, then you can create a vector calling non-default constructor as:

#include <vector> //header file where std::vector is defined

std::vector<MyClass>  arr(num, MyClass(10,20));

It creates a vector of num elements, each element is created by calling copy-constructor of the class, passing MyClass(10,20) as argument to it.

The vector is also good because now you dont need to manage memory yourself. Neither manual allocation, nor manual deallocation. Plus, you can know the number of elements by calling arr.size() anytime. You always know how many elements the vector contains. You can also add elements anytime, just by calling .push_back() member function as:

arr.push_back(MyClass(20,30)); 

And now you can access elements, just like you access array, i.e by using index:

f(arr[i]); // 0 <= i < arr.size();

Additionally, you can use iterators which facilitate idiomatic programming, enabling you to use various algorithmic functions from <algorithm> header as:

#include <algorithm> //header file where std::for_each is defined

std::for_each(arr.begin(), arr.end(), f);

where f is function which takes one argument of type MyClass& (or MyClass const &) depending on what you want to do in f.

In C++11, you can use lambda as:

std::for_each(arr.begin(), arr.end(), [](const MyClass & m)
                                      {
                                           //working with m 
                                      });

Leave a Comment