< Previous | Contents | Next >

The Lobby Class

The Lobby class represents the lobby or line in which players wait. Heres the class definition:

class Lobby

{

friend ostream& operator (ostream& os, const Lobby& aLobby);


public:

Lobby();

~Lobby();

void AddPlayer(); void RemovePlayer(); void Clear();


private:

Player* m_pHead;

};

The data member m_pHead is a pointer that points to a Player object, which represents the first person in line. m_pHead represents the head of the line.

Because each Player object has an m_pNext data member, you can link a bunch of Player objects in a linked list. Individual elements of linked lists are often

Introducing the Game Lobby Program 319



image

image

image

image

image

image

image

image

Figure 9.13

Each node holds a name and a pointer to the next player in the list. The first player in line is at the head.


called nodes. Figure 9.13 provides a visual representation of a game lobbya series of player nodes linked with one player at the head of the line.

One way to think about the player nodes is as a group of train cars that carry cargo and are connected. In this case, the train cars carry a name as cargo and are linked through a pointer data member, m_pNext. The Lobby class allocates memory on the heap for each Player object in the list. The Lobby data member m_pHead provides access to the first Player object at the head of the list.

The constructor is very simple. It simply initializes the data member m_pHead to

0, making it a null pointer.

Lobby::Lobby(): m_pHead(0)

{}

The destructor simply calls Clear(), which removes all the Player objects from the list, freeing the allocated memory.

Lobby::~Lobby()

{

Clear();

}

AddPlayer() instantiates a Player object on the heap and adds it to the end of the list. RemovePlayer() removes the first Player object in the list, freeing the allocated memory.

I declare the function operator<<() a friend of Lobby so that I can send a Lobby

object to cout using the << operator.

320 Chapter 9 n Advanced Classes and Dynamic Memory: Game Lobby


Tra p

image

The Lobby class has a data member, m_pHead, which points to Player objects on the heap. Because of this, I included a destructor that frees all of the memory occupied by the Player objects on the heap instantiated by a Lobby object to avoid any memory leaks when a Lobby object is destroyed. However, I didn’t define a copy constructor or overload the assignment operator in the class. For the Game Lobby program, this isn’t necessary. But if I wanted a more robust Lobby class, I would have defined these member functions.

image