13.4. Another constructor

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

card_deck::card_deck () {
  std::vector<playing_card> temp (52);
  cards = temp;

  std::size_t i = 0;
  for (int suit = clubs; suit <= spades; ++suit) {
    for (int rank = ace; rank <= king; ++rank) {
      cards[i].suit = static_cast<card_suit>(suit);
      cards[i].rank = static_cast<card_rank>(rank);
      i++;
    }
  }
}

Notice how similar this function is to build_deck, 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 card_deck deck;

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

Example c192_deck_constructor_ac_1
 1#include <cstddef>
 2#include <iostream>
 3#include <string>
 4#include <vector>
 5
 6enum card_suit { clubs, diamonds, hearts, spades };
 7
 8enum card_rank { ace=1, two, three, four, five, six, seven, eight, nine,
 9ten, jack, queen, king };
10
11struct playing_card {
12    card_rank rank;
13    card_suit suit;
14    playing_card ();
15    playing_card (card_suit s, card_rank r);
16    void print () const;
17};
18
19struct card_deck {
20    std::vector<playing_card> cards;
21    card_deck ();
22};
23
24int main() {
25    card_deck deck;
26    for (std::size_t i = 0; i < 52; i++) {
27        deck.cards[i].print();
28    }
29}

Based on your observations from the active code above, the cards in deck are initialized to the correct suits and ranks of a standard deck of 52 cards.

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.

  1.         i++;
          }
       }
    }
  2. card_deck::card_deck () {
  3. cards = temp;
    std::size_t i = 0;
  4. cards[i].suit = rank;
    cards[i].rank = suit;
  5. cards[i].suit = static_cast<card_suit>(suit);
    cards[i].rank = static_cast<card_rank>(rank);
  6. for (card_rank rank = ace; rank <= ten; rank = card_rank(rank+1)) {
  7. for (card_suit suit = clubs; suit < spades; suit = card_suit(suit+1)) {
  8. for (int rank = ace; rank <= king; ++rank) {
  9. for (int suit = clubs; suit <= spades; ++suit) {
  10. std::vector<playing_card> temp (40);
  11. std::vector<playing_card> temp (52);