Arrays and Classes

Arrays of Objects

Declaring

Initialization

Using


Arrays as Class Member Data


Card Game Example

This example program is a Blackjack card game simulation

Features include the following

Notes:

Here is a portion of the declaration of the Deck class, which shows the setup of an array of objects, in a composition ("has-a") relationship:
  class Deck 
   {  
   public: 
       ....		// member functions
   private: 
       int topCard;       // points to position of current top card of deck 
       Card cards[52];    // a deck is 52 cards. 
   }; 

Note the use of the topCard variable. While not data that the class user specifically sees or is interested in, it helps iterate through the array for dealing.

Here is a portion of the Player class:

   class Player 
   { 
   public: 
       ....		  // member functions
   private: 
       Card hand[5]; 
       int numCards;        // the number of cards currently in the hand 
       int HandValue();     // calculates the numeric value of the hand 
       void ShowHand();     // displays a player's hand and value 
   }; 

Note the numCards tracking variable. In this case, the array of Cards (called hand) can store up to 5 cards. Sometimes it's not full. numCards keeps track of how much of the allocated array is in use.

Example of numCards being used in a function:

   for (int i = 0; i < numCards; i++) 
       hand[i].Display();                // only displays the filled card slots