Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

This question already has an answer here:

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?

share|improve this question

marked as duplicate by n.m. c++ Jul 24 '14 at 3:26

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
Use a vector. You should be using one anyway. – chris Jul 24 '14 at 3:06

3 Answers 3

up vote 2 down vote accepted

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);
share|improve this answer
    
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 3: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 3:37
    
@keltar I got it! Thanks! – CyberLuc Jul 24 '14 at 3:45

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;

share|improve this answer
    
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 3:27

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;
share|improve this answer
    
Thanks, vector is enough for me. – CyberLuc Jul 24 '14 at 3:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.