Your class appears to be attempting to define an array of 'pointers to int
', not an array of int
as you suggest. However, the classic answer is precisely that you use a 'pointer to int
' and allocate the array in the constructor and release it in the destructor. To a first approximation:
class foo
{
public:
int *arr;
int s;
foo(int sz) : s(sz) { arr = new int [s]; }
~foo() { delete [] arr; }
};
If you're going to go down this route, you will also need to provide an assignment operator and a copy constructor (as Mike Seymour reminds me - thanks, Mike); the default versions the compiler will write for you if you don't write them for yourself will be wrong - horribly wrong. (The SO question "What is the Rule of Three?" covers this.)
However, this is (probably) not exception safe, and you'd be well advised to use std::vector<int>
instead of a plain pointer:
class foo
{
public:
std::vector<int> arr;
foo(int sz) : arr(sz) { }
};
You don't need to store the size explicitly; the vector does that for you.