views:

7842

answers:

7

In the code below I would like array to be defined as an array of size x when the Class constructor is called. How can I do that?

class Class
{
public:
  int array[];
  Class(int x) : ??? { }
}
+12  A: 

You can't initialize the size of an array with a non-const dimension that can be calculated at compile time (at least not in current C++ standard, AFAIK).

I recommend using std::vector<int> instead of array. It provides array like syntax for most of the operations.

Cătălin Pitiș
What would the syntax for using a vector in that situation be like?
zaratustra
vector< int > array; Class( x ) : array( x ) {};
DevSolar
+1  A: 

Instead of using a raw array, why not use a vector instead.

class SomeType {
  vector<int> v;
  SomeType(size_t x): v(x) {}
};

Using a vector will give you automatic leak protection in the face of an exception and many other benefits over a raw array.

JaredPar
Do you mean "Using *a vector* will give you automatic leak protection"? :)
Matt Kane
@mkb, that's twice today I've made fundamentally stupid comments. Must drink more coffee to wake up before i start posting ;)
JaredPar
+2  A: 

Use the new operator:

class Class
{
   int* array;
   Class(int x) : array(new int[x]) {};
};
John Dibling
Don't forget to call delete[] in the constructor if you use this code.
Brian
If you do this you will also need a copy constructor , an assignment operator and a destructor. Useing a std::vector gives you exactly the same functionality but requires none of these.
anon
A: 

You can't do it in C++ - use a std::vector instead:

#include <vector>

struct A {
   std::vector <int> vec; 
   A( int size ) : vec( size ) {
   }
};
anon
A: 

Declare your array as a pointer. You can initialize it in the initializer list later through through new.

Better to use vector for unknown size.

You might want to look at this question as well on variable length arrays.

Shree
better to use the vector for known size too
anon
have to agree on that
Shree
BAD idea. Doing the memory management on a pointer that acts like an array is not trivial in the presence of exceptions. Use std::vector or std::tr1::array.
Martin York
accepted, but this was just an option in response to the original question
Shree
+3  A: 

I don't think it can be done. At least not the way you want. You can't create a statically sized array (array[]) when the size comes from dynamic information (x).

You'll need to either store a pointer-to-int, and the size, and overload the copy constructor, assignment operator, and destructor to handle it, or use std::vector.

class Class
{
  ::std::vector<int> array;
  Class(int x) : array(x) { }
};
AFoglia
A: 

Two options:

Use std::vector. This allows easy re-sizing of the array.
Use std::tr1::array. This has a static size.

Both can be correctly initialized in the constructors initializer list.

Martin York