I have a dynamically allocated array of polymorphic objects that I would like to resize without using STL library (vectors, etc). I’ve tried moving the original to a temporary array, then deleting the original, then setting the original equal to the temporary, like this:
int x = 100;
int y = 150;
Animal **orig = new Animal*[x];
Animal **temp = new Animal*[y];
//allocate orig array
for(int n = 0; n < x; n++)
{
orig[n] = new Cat();
}
//save to temp
for(int n = 0; n < x; n++)
{
temp[n] = orig[n];
}
//delete orig array
for(int n = 0; n < x; n++)
{
delete orig[n];
}
delete[] orig;
//store temp into orig
orig = temp;
However, when I try to access the element for example:
cout << orig[0]->getName();
I get a bad memeory alloc error:
Unhandled exception at at 0x768F4B32 in file.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0033E598.
For this particular case, don’t do this. You are actually deleting the objects not the array. So all the objects in the temp array are pointing to invalid locations. Simply do
delete [] origto deallocate the original array.