You're leaking memory in remove(). In line 58, free the memory:
1 2
|
delete [] list;
list = l;
|
Also in your destructor (and elsewhere) instead of
, use
delete [] list;
In add(), follow the example of delete, reallocate memory of the right size.
is out of bounds.
1 2 3 4 5 6
|
int *l = new int[size + 1];
for(int i = 0; i < size; ++i) l[i] = list[i];
l[size] = d;
delete [] list;
list = l;
size+=1;
|
In clone(), you need to copy the list array, otherwise you'll end up with 2 objects woning the same array, it will thus get destroyed twice.
1 2 3 4 5
|
ArrayList clone(){
int *l = new int[size]; // calling length here is inefficient
for(int i = 0; i < size; ++i) l[i] = list[i];
return ArrayList(length(), l);
}
|
Generally speaking, allocating new memory and copying eveything each time you add or remove a single item is inefficient. You start with a reasonable sized buffer and track both the size of the buffer and the number of elements. Then you only need to allocate new memory when the buffer runs out. And when you're removing, you only need to move the items ahead of the element you're deleting back by one:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
int remove(int index)
{
int removed = -1;
if(checkIndex(index))
{
removed = list[index];
for( int i = index + 1; i < size ; i++ )
{
list[i] = list[i + 1];
}
size -= 1;
}
else
{
cout << "Index Out of bound\n";
// you should throw an exception here, there's no valid return value
}
return removed;
}
|
Also don't forget to return values when you promise to do so remove(), get()).
I suggest a different indentation style as well, your code is very difficult to read, and mistakes are very likely, especially with multiple statements and conditionals on one line.
Finally, if you're not doing this just for practice, if this is a class you actually intend to use, then have a look at the standard library for much better alternatives. In any case have a look at the standard library for alternatives to raw pointers.