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.


In the previous chapter, we worked with a vector of objects, but I also mentioned that it is possible to have an object that contains a vector as an instance variable. In this chapter I am going to create a new object, called a Deck, that contains a vector of Cards.

The structure definition looks like this

struct Deck {
  pvector<Card> cards;

  Deck (int n);

Deck::Deck (int size)
  pvector<Card> temp (size);
  cards = temp;

The name of the instance variable is cards to help distinguish the Deck object from the vector of Cards that it contains.

For now there is only one constructor. It creates a local variable named temp, which it initializes by invoking the constructor for the pvector class, passing the size as a parameter. Then it copies the vector from temp into the instance variable cards.

Now we can create a deck of cards like this:

  Deck deck (52);

Here is a state diagram showing what a Deck object looks like:

The object named deck has a single instance variable named cards, which is a vector of Card objects. To access the cards in a deck we have to compose the syntax for accessing an instance variable and the syntax for selecting an element from an array. For example, the expression[i] is the ith card in the deck, and[i].suit is its suit. The following loop

  for (int i = 0; i<52; i++) {[i].print();

demonstrates how to traverse the deck and output each card.

Last Update: 2005-12-05