The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

Deck Member Functions

Now that we have a Deck object, it makes sense to put all the functions that pertain to Decks in the Deck structure definition. Looking at the functions we have written so far, one obvious candidate is printDeck (Section 12.7). Here's how it looks, rewritten as a Deck member function:

void Deck::print () const {
  for (int i = 0; i < cards.length(); i++) {
    cards[i].print ();

As usual, we can refer to the instance variables of the current object without using dot notation.

For some of the other functions, it is not obvious whether they should be member functions of Card, member functions of Deck, or nonmember functions that take Cards and Decks as parameters. For example, the version of find in the previous chapter takes a Card and a Deck as arguments, but you could reasonably make it a member function of either type. As an exercise, rewrite find as a Deck member function that takes a Card as a parameter.

Writing find as a Card member function is a little tricky. Here's my version:

int Card::find (const Deck& deck) const {
  for (int i = 0; i <; i++) {
    if (equals ([i], *this)) return i;
  return -1;

The first trick is that we have to use the keyword this to refer to the Card the function is invoked on.

The second trick is that C++ does not make it easy to write structure definitions that refer to each other. The problem is that when the compiler is reading the first structure definition, it doesn't know about the second one yet.

One solution is to declare Deck before Card and then define Deck afterwards:

// declare that Deck is a structure, without defining it
struct Deck;

// that way we can refer to it in the definition of Card
struct Card
  int suit, rank;

  Card ();
  Card (int s, int r);

  void print () const;
  bool isGreater (const Card& c2) const;
  int find (const Deck& deck) const;

// and then later we provide the definition of Deck
struct Deck {
  pvector<Card> cards;

  Deck ();
  Deck (int n);
  void print () const;
  int find (const Card& card) const;

Last Update: 2005-12-05