I am trying to write a simpler version of a zoo tycoon game that allows the user to buy animals. I have a class, Zoo that has it's own class, lion. Each time a lion is bought I want to create a lion object that is stored in an array on the heap, so it needs to use 'new'. My problem is, after instantiating the first lion, all subsequent lion's address' in their constructor is different than the address where I give them a random age!
Zoo.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
#ifndef ZOO_H
#define ZOO_H
#include "Lion.h"
class Zoo
{
private:
Lion *lion;
int turn;
int index;
public:
Zoo():lion(new Lion[1] ), turn(0),index(0)
{
//cout<<"Zoo constructor at " << this << endl;
cout << endl;
}
void gameLoop()
{
int x = 0;
while (turn < 2)
{
if (turn == 0)
{
lion[index].data(lion);
turn++;
}
else
{
index++;
lion[index].data(new Lion[1]);
turn++;
}
}
}
~Zoo()
{
cout << "Zoo destruct" << " at " << this << endl;
delete[] lion;
}
};
#endif
|
Lion.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#ifndef LION_H
#define LION_H
#include<iostream>
using namespace std;
class Lion
{
private:
int age;
public:
Lion():age(0)
{
cout << "Lion construct at address "<<this << endl;
}
void data(Lion* L)
{
age = rand() % 500 + 1;
cout << "age: " << age << " address " << this << endl;
}
~Lion()
{
cout << "Lion destruct" << endl;
}
};
#endif
|
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12
|
#include"Zoo.h"
int main()
{
Zoo zoo;
zoo.gameLoop();
system("Pause");
return 0;
}
|
My problem seems to arise from this section
else
{
index++;
lion[index].data(new Lion[1]);
turn++;
}
The new constructor that
lion[index].data(new Lion[1]);
creates always has a different address than what is shown in display for every increment of turn after 0.
Not sure how I make the addresses the same!
My output is
Lion construct at address 012F21A4
age: 42 address 012F21A4
Lion construct at address 012F239C
age: 468 address 012F21A8
Press any key to continue . . .