13.4. Another constructor

Now that we have a Deck object, it would be useful to initialize the cards in it. From the previous chapter we have a function called buildDeck that we could use (with a few adaptations), but it might be more natural to write a second Deck constructor.

Deck::Deck () {
  vector<Card> temp (52);
  cards = temp;

  int i = 0;
  for (Suit suit = CLUBS; suit <= SPADES; suit = Suit(suit+1)) {
    for (Rank rank = ACE; rank <= KING; rank = Rank(rank+1)) {
      cards[i].suit = suit;
      cards[i].rank = rank;
      i++;
    }
  }
}

Notice how similar this function is to buildDeck, except that we had to change the syntax to make it a constructor. Now we can create a standard 52-card deck with the simple declaration Deck deck;

The active code below prints out the cards in a deck using the loop from the previous section.

Let’s write a constructor for a deck of cards that uses 40 cards. This deck uses all 4 suits and ranks Ace through 10, omitting all face cards.

You have attempted of activities on this page