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:

I am trying to initialize array of objects with the same value

class A
{
   A(int a1)
   {
      var1 = a1;
   }

   var1;
}

int main(void)
{
    // I want to initialize all the objects with 5 without using an array 
    A *arr = new A[10](5); // How to use the constructor to do something like this
    return 0;
}

As i want to pass the same value to all the objects, is there a way to avoid using an array. i.e. I want to avoid doing the following:

A *arr = new A[10]{5, 5, 5, 5, 5, 5, 5, 5, 5, 5}
share|improve this question
    
The easy answer is to use a vector, but I assume that's out of the question for some reason. – chris Sep 3 at 22:59
    
Since it is an int array, how about a simple memset() call? – REACHUS Sep 3 at 23:00
    
@chris yes vector is not an option for me for some reason. – Siddharth Sep 3 at 23:01
    
@REACHUS the int is just for example. The actual array can be pretty large with some other params in constructor so I was trying to see if the unnecessary memory can be avoided. – Siddharth Sep 3 at 23:02
    
Or std::array which has a fill function? – Gary Buyn Sep 3 at 23:04

1 Answer 1

up vote 4 down vote accepted

Normally we avoid raw pointers, especially when not encapsulated in std::unique_ptr or other automatic (RAII) pointer types.

Your first choice should be std::array if size is known at compile time, or std::vector if you want dynamic size or a very large array.

The second choice, if you insist on managing the memory yourself, is to use std::fill or std::fill_n from <algorithm>.

In this case, std::fill_n is probably cleaner:

A *arr = new A[10];
std::fill_n( &arr[0], 10, A(5) );

Please at least consider automatic pointer management though:

std::unique_ptr<A[]> arr( new A[10] );
std::fill_n( &arr[0], 10, A(5) );
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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