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.
- True - we used the buildDeck function with a few modifications to do this.
- How do we create the deck?
- True - we wrote a Deck constructor to do this.
- The for loops in the Deck constructor initialize each card to its proper value.
- False - we used the buildDeck function with a few modifications to do this.
- Look at the active code. How do we create the deck?
- False - we wrote a Deck constructor to do this.
- Look at the active code.
Q-2: 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.