Polymorphism and Arrays
Posted: Mon Jan 24, 2011 9:35 pm
I'm trying to create a class Deck (IE a deck of cards) that works with arrays of class Card. The part I'm having trouble with is that I want this deck to work with all kinds of cards and am therefore working with classes that inherit the class Card (In this case a class ResourceCard : public Card.) What I would like to be able to do is initialize an instance of Deck with an array of ResourceCard. Since they will have different memory sizes, I'm not sure polymorphism/casting can help me.
So I realize I'm accessing memory I shouldn't since I'm sending an array of ResourceCard which takes up more memory than regular old Card. My question is, how do I fix this? It seems to me there should be a way to do this (or at least something like this.)
Code: Select all
int main()
{
ResourceCard resourceCard;
ResourceCard resourceCards[5];
//enum Resource { NONE, WATER, FOREST, HILL, MOUNTAIN , ANY };
resourceCard.setType( ANY );
resourceCards[0] = resourceCard;
resourceCard.setType( WATER );
resourceCards[1] = resourceCard;
resourceCard.setType( FOREST );
resourceCards[2] = resourceCard;
resourceCard.setType( HILL );
resourceCards[3] = resourceCard;
resourceCard.setType( MOUNTAIN );
resourceCards[4] = resourceCard;
Deck deck( resourceCards , 5 );
cin.get();
return 0;
}
Code: Select all
//The constructor I'm using
Deck::Deck( Card p_newCards[] , int p_count )
{
cardsInDeck = new Card[DECK_SIZE_LIMIT];
count = 0;
discardedCards = new Card[DECK_SIZE_LIMIT];
discardCount = 0;
lastDrawnCard = NULL;
if( p_count <= DECK_SIZE_LIMIT && p_count > 0)
{
count = p_count;
for( int i = 0 ; i < count ; i++ )
{
cardsInDeck[i] = p_newCards[i]; //This line causes the program crash on it's second iteration
}
}
}