Section 3 - A Card Game

1A.3.1 A Class for a Deck of Cards

Do you play Bridge, Hearts, Poker or Black Jack?  If so, you've signed up for the right class.  Our first example will deal (ahem) with the topic of playing cards.

We will create a class called Card whose objects we will imagine to be representations of playing cards.  Each object of the class will be a particular card such as the '3' of clubs or 'A' of spades.  The private data of the class is fairly obvious. We will need a card value ('A', '2', '3', ... 'Q', 'K') and a suit (spades, hearts, diamond, clubs).

Before we design this class, let's see a very simple main() (also called the client, since it uses, or employs, our class) that simply declares a few Card objects and displays their values on the screen.  We want to do a lot of fun things with our Card objects, but not yet.  We start very carefully and slowly.

int main()
{
    Card card1, card2('5'), card3('9', hearts),
    card4('j', clubs), card5('1', diamonds);

    if ( ! card1.set(2, clubs) )
        cout << "incorrect value (2, clubs) passed to card::set()\n\n";
    if ( ! card1.set('2', clubs) )
        cout << "incorrect value ('2', clubs) passed to card::set()\n\n";

    cout << card1.toString() << endl << card2.toString() << endl <<
    card3.toString() << endl << card4.toString() << endl
    << card5.toString() << endl<< endl;

    card1 = card4;

    cout << "after assigning card4 to card1:\n";
    cout << card1.toString() << endl << card4.toString() <<  endl << endl;
    return 0;
}

We can't run this main() without embedding it into a full program that has all of the Card class definitions, but let's look at a copy of the run anyhow, so we can see what the correct output for this program is:

screen shot

We can learn a lot about what this class Card must be and do by looking at the main() and the run.  Let's make a list of things that we can surmise just by looking at the client.

Evidently, in order to fully understand how to write this class, we are going to have to become familiar with three simple C++ topics:

  1. Enum types
  2. Default parameters
  3. The newer string class and the older CString char arrays.

We will spend the next three sections explaining those topics then return to play some cards.