< Previous | Contents | Next >

The Lobby::AddPlayer() Member Function

The Lobby::AddPlayer() member function adds a player to the end of the line in the lobby.

void Lobby::AddPlayer()

{

//create a new player node

cout << "Please enter the name of the new player: "; string name;

cin >> name;

Player* pNewPlayer = new Player(name);


//if list is empty, make head of list this new player if (m_pHead == 0)

{

m_pHead = pNewPlayer;

}

//otherwise find the end of the list and add the player there else

{

Player* pIter = m_pHead; while (pIter->GetNext() != 0)

{

pIter = pIter->GetNext();

}

pIter->SetNext(pNewPlayer);

}

}

The first thing the function does is gets the new players name from the user and use it to instantiate a new Player object on the heap. Then it sets the objects pointer data member to the null pointer.

Introducing the Game Lobby Program 321


Next, the function checks to see whether the lobby is empty. If the Lobby objects data member m_pHead is 0, then theres no one in line. If so, the new Player object becomes the head of the line and m_pHead is set to point to a new Player object on the heap.

image

image

image

image

image

If the lobby isnt empty, the player is added to the end of the line. The function accomplishes this by moving through the list one node at a time, using pIters GetNext() member function, until it reaches a Player object whose GetNext() returns 0, meaning that its the last node in the list. Then, the function makes that node point to the new Player object on the heap, which has the effect of adding the new object to the end of the list. Figure 9.14 illustrates this process.



image image image


image


image

image

image

image

image

Figure 9.14

The list of players just before and just after a new player node is added.

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


Tra p

image

Lobby::AddPlayer() marches through the entire list of Player objects every time it’s called. For small lists this isn’t a problem, but with large lists this inefficient process can become unwieldy. There are more efficient ways to do what this function does. In one of the chapter exercises, your job will be to implement one of these more efficient methods.

image