5 Creating and using objects and arrays

 

This chapter covers

  • Writing a class or structure
  • Scoped enums
  • Using an array instead of a vector when we know how many elements we need
  • Writing a comparison operator
  • Defaulted functions
  • Using std::variant

In this chapter, we will create a deck of cards and write a higher-or-lower card game for guessing whether the next card from a deck is higher or lower. We will create a class for a card and store a deck of cards in an array. We need to consider how to define comparison operators for our cards, as well as how to write constructors and other member functions. We’ll need to use a random shuffle too. We will then extend the game to include jokers and learn how to use std::variant. By the end of the chapter, we will have a working card game and be ready to do more with classes.

5.1 Creating a deck of playing cards

We will start by defining a card class. We can declare a card using either the keyword class or struct. If we use a struct, everything is public by default, which is a simple starting point. A card has a suit and a value. There are four suits and 13 possible values per suit: 1, or ace; 2 up to 10; and three court cards. We will also need to display and compare cards, as well as a way to create a whole deck. We will start with the cards themselves.

5.1.1 Defining a card type using a scoped enum for the suit

5.1.2 Defining a card type using a strong type for the face value

5.1.3 Constructors and default values

5.1.4 Displaying playing cards

5.1.5 Using an array to make a deck of cards

5.1.6 Using generate to fill the array

5.1.7 Comparison operators and defaults

5.2 Higher-or-lower card game

5.2.1 Shuffling the deck

5.2.2 Building the game

5.2.3 Using std::variant to support cards or jokers