I don't think any of the replies so far have addressed the actual problem here.
The problem is this:
|
Parent* array = new A[QUANTITY]; // THIS IS BAD
|
Polymorphism allows for a Parent* to point to a
single A object... however it cannot point to an
array of A's because the objects have different sizes. By doing this, only the first pointer in your 'array' will be valid. All other pointers will become corrupt... and therefore will likely segfault/crash when deleted.
To explain why this is the case....the compiler uses the pointer type to do some "behind the scenes" pointer math whenever you access elements. Here's an example:
1 2 3 4 5
|
int* example = new int[5];
cout << "[0] = " << &example[0] << "\n";
cout << "[1] = " << &example[1] << "\n";
cout << "[2] = " << &example[2] << "\n";
|
Assuming
sizeof(int)==4
you will notice that each value printed will be 4+the previous. So output might look like this:
[0] = 00010000
[1] = 00010004
[2] = 00010008
|
The compiler is using
sizeof(int)
because
example
is an int pointer. If example was a double pointer, it would use
sizeof(double)
.
Coming back to your example with a Parent and Child class:
1 2 3 4 5
|
Parent* ptr = new Parent[5];
cout << "[0] = " << &ptr[0] << "\n";
cout << "[1] = " << &ptr[1] << "\n";
//...
|
Assuming
sizeof(Parent)==0x10
, this might output something like:
[0] = 00010000
[1] = 00010010
[2] = 00010020
...
|
Again, because the compiler is using sizeof(Parent) to determine where further elements are.
Another example with the child class 'A':
1 2 3 4 5
|
A* ptr = new A[5];
cout << "[0] = " << &ptr[0] << "\n";
cout << "[1] = " << &ptr[1] << "\n";
//...
|
where sizeof(A)==0x20
[0] = 00010000
[1] = 00010020
[2] = 00010040
|
Again, what you'd expect.
The thing to note here is that sizeof(A) is always going to be >= sizeof(Parent) because an A will contain everything its Parent does, and also possibly some additional information specific to A.
With this in mind... take a look at what you're doing:
1 2 3 4 5
|
Parent* ptr = new A[5]; // BAD BAD BAD
cout << "[0] = " << &ptr[0] << "\n";
cout << "[1] = " << &ptr[1] << "\n";
//...
|
[0] = 00010000
[1] = 00010010
[2] = 00010020
|
Since 'ptr' is a
Parent
pointer, the compiler thinks each element is
sizeof(Parent)
bytes. However they're actually
sizeof(Child)
bytes. As a result...
&ptr[1]
is a bad pointer! It doesn't point to an object, it actually points to memory smack in the middle of the first element.
how to solve it if I insist to use Parent *array; in line 40 ? |
You can't. You don't have an array of Parents, you have an array of As. You must use the correct pointer type.