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 variants
In this chapter, we will create a deck of cards, and write a higher/lower game, 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 random shuffle too. 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 either declare a card using 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, one, or ace, two up to ten, then three court cards. We will also need to display and compare cards, and a way to create a whole deck. We will start with the cards themselves.