Your example is working fine - just take care to delete[]
with new[]
allocated space accordingly after you're finished (to prevent memory leaking). Also instead of using 15 as hardcoded constant, you probably want to use the parameter size
(otherwise for arrays bigger than 15 elements, you would have an memory access violation).
class ArrayClass{
public:
ArrayClass(int* array, int size){
a = new int[size];
for (int i(0); i < size; i++) {
this->a[i] = array[i];
}
this->size = size;
}
virtual ~ArrayClass(){
delete[] a;
}
private:
int* a;
int size;
};
int main(int argc, char** argv){
int array[3] = { 1, 2, 3 };
ArrayClass a2(array, 3);
return 0;
}
Arrays can be allocated in C++ in different ways:
int a[3]; // will allocate the space for 3 elements statically from the stack
int* a = new int[3]; // will allocate space for 3 elements dynamically from the heap
Basically it decides in which memory your array will be located - but there are many differences in these two methods involved - see i.e. What and where are the stack and heap?.
Some main differences are:
- stack allocations can't use a dynamical length like a variable i.e.
int size = 10; int a[size]; // <- is invalid
- stack allocations are 'deleted' automatically when they are out-of-scope
- heap allocations have to be
deleted[]
explicit to not leak memory
The line int* a = new int[3];
will declare a pointer-variable to an memory location where 3 int
values can fit in. So after the declaration these 3 values can be addressed directly as a[0]
, a[1]
and a[2]
. After all operations are finished delete[] a;
is necessary. Because if the pointer a*
is getting out-of-scope (i.e. end of your function) the memory for the 3 values is not deallocated automatically.