I’m currently working on a Poker game for C++, and I’m having trouble properly updating a data member for one of my class objects. The game currently uses four classes: Game, Player, Hand, and Card (I’m not focusing on my House class just yet). Game contains the Player objects (number defined by user), Player contains a Hand object, and Hand contains the Card object (two cards for each player). Here’s the relevant code I have so far:
The game is immediately ran from main() via a new Game object. After the number of players and player names are assigned to each player object, the player information is displayed (for testing purposes).
#include <iostream>
using namespace std;
Game::Game() : numPlayers(0), players(NULL)
{
numPlayers = promptNumPlayers();
players = new Player[numPlayers];
cout << endl;
for (int i = 0; i < numPlayers; i++)
players[i].setName(promptName(i+1));
play();
}
void Game::play()
{
cout << endl;
for (int i = 0; i < numPlayers; i++)
cout << *(players+i); //displays incorrect hand
}
In this cout test, the player’s information is displayed properly (albeit the same cards, but I will fix that later). I suppose this means that my Hand and Card classes are okay for now, but I’ll post those if necessary.
Player::Player() : name(""), money(10000), playerHand(NULL)
{
Hand newHand(NUM_CARDS);
Hand *tempPtr = &newHand;
playerHand = tempPtr;
cout << *playerHand; //displays correct hand
}
ostream& operator<<(ostream &out, const Player &aPlayer)
{
out << "\n* " << aPlayer.name << ": ";
out << "$" << aPlayer.money << " ";
out << *(aPlayer.playerHand);
return out;
}
In the play() function, however, the player’s hand is blank. I’m not sure if I’m improperly updating playerHand, or if some data is being destroyed when I try to display it in play(). Is Player’s constructor incorrect, or do I need to add more code somewhere else? I’ve tried using a setter for Hand, but it hasn’t worked out so far.
If I change the output operator to display playerHand’s memory address, the player’s constructor will still display the correct hand, and play() will instead display the memory address. Otherwise, I think it works correctly.
I’ve come across a similar problem in one of my other programs, but I was able to fix it myself. I assume this issue is a bit more complex because I’m using an additional class in this program for holding this data.
You are assigning to
playerHanda reference to an object that has automatic allocation on stack.You should allocate it on heap:
Otherwise what happens is that the hand is allocated on stack inside the constructor, when the variable
newHandgoes out of scope it is released since stack is fred so the pointerplayerHandis not valid anymore.Remember to release its memory through
delete playerHandinPlayerdestructor.