13.3. DecksΒΆ

In the previous chapter, we worked with a vector of objects, but I also mentioned that it is possible to have an object that contains a vector as an instance variable. In this chapter I am going to create a new object, called a card_deck, that contains a vector of playing_cards.

The structure definition looks like this

struct card_deck {
  std::vector<playing_card> cards;

  card_deck (std::size_t n);
};

card_deck::card_deck (std::size_t size) {
  std::vector<playing_card> temp (size);
  cards = temp;
}

The name of the instance variable is cards to help distinguish the card_deck object from the vector of playing_cards that it contains.

For now there is only one constructor. It creates a local variable named temp, which it initializes by invoking the constructor for the vector class, passing the size as a parameter. Then it copies the vector from temp into the instance variable cards.

Now we can create a deck of cards like this:

card_deck deck (52);

Here is a state diagram showing what a card_deck object looks like:

image

The object named deck has a single instance variable named cards, which is a vector of playing_card objects. To access the cards in a deck we have to compose the syntax for accessing an instance variable and the syntax for selecting an element from an array. For example, the expression deck.cards[i] is the ith card in the deck, and deck.cards[i].suit is its suit. The following loop

for (std::size_t i = 0; i<52; i++) {
  deck.cards[i].print();
}

demonstrates how to traverse the deck and output each card.

A euchre deck consists of 9's, 10's, Jacks, Queens, Kings, and Aces. If we wanted to create a deck that is the size of the euchre deck, we would type: card_deck euchre_deck ;

Take a look at the state diagram above. When we create a deck of cards using Deck deck (52), what is true about our new deck?

ACE corresponds to a rank of value 0.