this is my addCard function which takes a playingCard as a parameter then hands over the address of its self to an allocated array of pointers to playingCard objects.
void cardHand::addCard(playingCard card) {
theHand[nElems++] = &card;
} // addCard()
now when i run my program it runs fine but then crashes when the destructor is called.
cardHand::~cardHand() {
for(int c = 0;c<MAX;c++) {
if(theHand[c] != NULL)
delete theHand[c]; // here is the problem
}
delete [] theHand;
} // class destructor
is it crashing because I’m only handing over the address of the playingCard object in the addCard function. should it be a pointer instead?
The problem is here
void cardHand::addCard(playingCard card) { theHand[nElems++] = &card; }You store address of the temporary card object which will be destructed at the end of the addCard method.
And in your destructor you attempt to delete it again.
You have two options.
First: make addCard to accept just card configuration and create your card with
newin theaddCardmethod.Second: accept card by pointer but then your cardHand’s destructor can’t be responsible for card deletion. And deletion will perform Deck object which created all the cards.