< Previous | Contents | Next >

The GenericPlayer Class

I define the GenericPlayer class for a generic Blackjack player. It doesnt represent a full player. Instead, it represents the common element of a human player and the computer player.

class GenericPlayer : public Hand

{

friend ostream& operator<<(ostream& os,

const GenericPlayer& aGenericPlayer);


public:

GenericPlayer(const string& name = ""); virtual ~GenericPlayer();

//indicates whether or not generic player wants to keep hitting virtual bool IsHitting() const = 0;


//returns whether generic player has busted - has a total greater than 21 bool IsBusted() const;


//announces that the generic player busts void Bust() const;

Introducing the Blackjack Game 367



protected:

string m_Name;

};


GenericPlayer::GenericPlayer(const string& name): m_Name(name)

{}


GenericPlayer::~GenericPlayer()

{}


bool GenericPlayer::IsBusted() const

{

return (GetTotal() > 21);

}


void GenericPlayer::Bust() const

{

cout << m_Name << " busts.\n";

}

I make the overloaded operator<<() function a friend of the class so I can display GenericPlayer objects on the screen. It accepts a reference to a GenericPlayer object, which means that it can accept a reference to a Player or House object, too.

The constructor accepts a string object for the name of the generic player. The destructor is automatically virtual because it inherits this trait from Hand.

The IsHitting() member function indicates whether a generic player wants another card. Because this member function doesnt have a real meaning for a generic player, I made it a pure virtual function. Therefore, GenericPlayer becomes an abstract class. This also means that both Player and House need to implement their own versions of this member function.

The IsBusted() member function indicates whether a generic player has busted. Because players and the house bust the same wayby having a total greater than 21I put the definition in this class.

The Bust() member function announces that the generic player busts. Because busting is announced the same way for players and the house, I put the definition of the member function in this class.

368 Chapter 10 n Inheritance and Polymorphism: Blackjack