I am creating a poker program for school (learning classes). The instruction are to make a class CARD and a class DECK with associated files. DECK is to be a vector of cards.
I have created the classes but am having a hard time with understanding how they work together. My main problem seems to be that I am not creating the DECK correctly. In the DECK constructor function I can access & manipulate the vector normally, but all other functions do not work. It seems like the DECK is not being created from CARD class in the proper manner.
When my DECK constructor calls function init() I get an error saying that the vector is out of range. If I move the init() function code into the constructor function, it works fine.
Please let me know where I am going wrong with this. Thanks.
/* Deck.h Deck.h Deck.h */
#pragma once
#include <vector>
#include "card.h"
usingnamespace std;
//define class 'deck'. It is a vector of cards. Functions should include shuffle, deal.
class deck
{
public:
deck ();
void init();
void shuffle ();
void deal ();
private:
vector<card> myDeck;
};
/* card.h card.h card.h */
#pragma once
usingnamespace std;
//define class 'card'. Card objects have no functions. They only contain data: (char)face, (char)suit, (int)pointVal.
class card
{
public:
char face;
char suit;
int pointVal;
};
This problem jumped out at me when I first saw your listing
1 2 3 4 5 6 7 8 9 10 11 12
for (int i=0; i<DECKSIZE; i++)
{
if (i <= 12)
myDeck[i].suit = 'c';
elseif (i <= 25)
myDeck[i].suit = 'd';
elseif (i <= 38)
myDeck[i].suit = 'h';
elseif (i <= 51) // i will ALWAYS be less than DESKSIZE ( or 52 ), so myDeck[i] will be assigned an 's'
// You could use the && command, as in 'if(i>12 && i<=25)' adjusting the numbers on the way down the for loop
myDeck[i].suit = 's';
} //close for loop
@whitenite1
When one if condition is true, the rest are ignored. So his if/else statements are actually fine.
@OP
You create a brand new vector in your constructor. Your member variable, however, is still an empty vector. So, when you call init, everything is out of bounds. When you move your init implementation into your constructor, only the local variable is modified, leaving your member untouched.
1 2 3
deck::deck()
: myDeck(DECKSIZE) //Called initialization list
{this->init();}
Or, if you are still unfamiliar with initialization lists, this will work fine as well: