It's been a full semester since I've taken Data Structures so I decided to work on a project to refresh my memory.
I am building a dice game where the user defines the number of players. There's a lot of functions missing but I've included those that the program needs to run smoothly.
Proper destruction was occurring before I implemented and use Player
type functions. Now, when *temp
tries to leave scope of Player storeName(Player *p)
, a break point is triggered at ~Player() { delete[] player; }
and I can't understand why.
Note* The functions that I am not including are also type Player
.
Here's an image for reference [1]: https://i.stack.imgur.com/Ib9WB.jpg
Any advice is appreciated.
struct Player {
int* qualifiers;
int matchPoints;
int totalWins;
int numOfRolls;
string name;
Player() { qualifiers = new int[2]; }
~Player() { delete[] qualifiers; }
};
class Midnight {
public:
Midnight(int numOfPlayers) {
index = 0;
m_numOfPlayers = numOfPlayers;
player = new Player[m_numOfPlayers];
for (int i = 0; i < m_numOfPlayers; i++) {
player[i].matchPoints = 0;
player[i].totalWins = 0;
player[i].numOfRolls = 0;
for (int j = 0; j < 2; j++) {
player[i].qualifiers[j] = 0;
}
}
dice = new int[player->numOfRolls];
for (int i = 0; i < player->numOfRolls; i++) {
dice[i] = 0;
}
}
void welcome();
Player storeName(Player* p);
Midnight(const Midnight& source);
Midnight operator=(const Midnight& source) {
delete[] player;
if (&source == this) {
return *this;
}
index = source.index;
m_numOfPlayers = source.m_numOfPlayers;
player = new Player[m_numOfPlayers];
for (int i = 0; i < m_numOfPlayers; i++) {
player[i].matchPoints = source.player[i].matchPoints;
player[i].totalWins = source.player[i].totalWins;
player[i].numOfRolls = source.player[i].numOfRolls;
player[i].name = source.player[i].name;
for (int j = 0; j < 2; j++) {
player[i].qualifiers[j] = source.player[i].qualifiers[j];
}
}
for (int i = 0; i < player->numOfRolls; i++) {
dice[i] = source.dice[i];
}
return *this;
}
~Midnight() {
delete[] player;
}
private:
int m_numOfPlayers;
Player* player;
int *dice;
int index;
};
void Midnight::welcome() {
// say stuff
storeName(player);
}
// Store Name
Player Midnight::storeName(Player* p){
Player* temp = p;
// do stuff
return *temp;
}
int main() {
int players = 0;
cout << "Enter a number of players: " << endl;
cin >> players;
Midnight Play(players);
Play.welcome();
}