1 2 3 4 5 6 7
|
Organism *R, *G, *P;
[snip]
P = new Plant[NumPlants];
G = new Goldfish[NumGoldfish];
R = new Redfish[NumRedfish];
|
You can't do this.
Plant and Fish are larger types than Organism (sizeof(Plant) > sizeof(Organism))
Say, for example, You have the following sizes (note this is not realistic, I'm just using easy numbers so you can visualize):
sizeof(Organism) == 10
sizeof(Plant) == 12
now when you do
new Plant[2];
memory for 2 plants is allocated. One Plant is placed at address 'X', and the other is placed at address X+12. X is then assigned to your 'P' pointer.
The problem here, is that the compiler doesn't know that P points to plants. It thinks it points to Organisms. So when you do
P[1]
, it actually looks at address X+10, not X+12 (it uses sizeof(Organism) instead of sizeof(Plant)). So you're basically getting scrambled data.
Also, this is unrelated but...
1 2 3 4
|
void Plant::Reset()
{
Plant(2);
}
|
This doesn't do what you expect. You can never "reconstruct" an object. ctors are called once and only once.
What this code actually does is it creates a new temporary object and constructs that, but it doesn't actually reconstruct this object. IE: it's basically the same as:
1 2 3 4
|
void Plant::Reset()
{
Plant temp(2);
}
|
only 'temp' is nameless in your code.