3

I wrote a class, something like this (just for demonstration) :

class cls{
public:
    cls(int a):value(a){}
private:
    int value;
};

And I want to dynamically create an array, each element initialized to a specific value like 2:

cls *arr = new cls[N](2);

But g++ reported 'error: parenthesized initializer in array new'.

I searched the Internet, but only to find similar questions about basic types like int and double, and answer is NO WAY.

Suppose the class must be initialized, how to solve the problem? Do I have to abandon constructer?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
CyberLuc
  • 317
  • 1
  • 2
  • 8

3 Answers3

6

You can:

cls *arr = new cls[3] { 2, 2, 2 };

If you use std::vector, you can:

std::vector<cls> v(3, cls(2));

or

std::vector<cls> v(3, 2);
M.M
  • 138,810
  • 21
  • 208
  • 365
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Thanks. I tried vector and use constructor to print a string at the same time. The string shows only once, but I checked every element is initialized. Seems vector only initializes once, then copy the one to the remaining objects. – CyberLuc Jul 24 '14 at 03:32
  • @Twisx constructor called when you used `cls(2)` manually and passed it to vector initialisation. Then copy constructor used to fill elements. – keltar Jul 24 '14 at 03:37
5

Use a vector.

If you insist on using a dynamically allocated array instead of std::vector, you have to do it the hard way: allocate a block of memory for the array, and then initialize all the elements one by one. Don't do this unless you really can't use a vector! This is only shown for educational purposes.

cls* arr = static_cast<cls*>(::operator new[](N*sizeof(cls)));
for (size_t i = 0; i < N; i++) {
    ::new (arr+i) cls(2);
}
// ::delete[] arr;
Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • Thanks, vector is enough for me. – CyberLuc Jul 24 '14 at 03:34
  • Thank you for this obscure answer. It came in very handy for me in my use case: I needed a pointer to an array of objects that lack a default constructor to be queued to another thread which will later destroy the memory when it's no longer needed. I wouldn't have been able to do that with a vector. I'll admit it's less pretty, but it gets the job done. – mkrufky Oct 02 '17 at 08:46
1

You can also use vectors

#include <vector>

using namespace std;

class cls{
public:
    cls(int a):value(a){}
private:
    int value;
};

int main() {

vector<cls> myArray(100, cls(2));

return 0;
}

That creates a vector (an array) with 100 cls objects initialized with 2;

tpdietz
  • 1,358
  • 9
  • 17
  • Thanks. I tried vector and use constructor to print a string at the same time. The string shows only once, but I checked every element is initialized. – CyberLuc Jul 24 '14 at 03:27