One of the most probable reasons why Data* arr = new Data[len];
wouldn't work is because type Data
has no default constructor, i.e. Data::Data()
.
But no matter whether Data
has a default constructor or not, it's not a good idea to try to create an array like this anyway. Once you dynamically allocate it with new[]
you commit yourself to take care of ugly memory management connect with it. It's much better idea to use one of STL containers such as std::vector
(#include <vector>
required) that will take care of memory management for you.
Then you have several options:
std::vector<Data> v; // option 1
v.reserve(len);
// in loop:
v.push_back(Data(x, y)); // there could be different values
std::vector<Data> v2(len); // option 2
std::vector<Data> v3(len, Data(12,12)); // option 3
First option will fit almost any situation. It prepares the chunk of memory big enough to hold len
elements and then you can just fill v
in convenient but still very efficient manner. Option 2 requires Data
to have default constructor, which is solved by option 3 that uses your custom constructor to construct elements.
All mentioned options result in std::vector
object with automatic storage duration being created. Note that all elements are stored in a continuous block of memory, so you can use &v[0]
to initialize the pointer to its first element and work with it in a same way you would work with dynamically allocated array.