Original Post
Hello everyone, I am reading "Beginning C++ Game Programming" and I am stuck with Exersize 1 in chapter 9. I am trying to write a copy constructor and it blows up. What am I doing wrong here?
// Game Lobby 2.0 Exersize Enhancements
// Simulates a game lobby where players wait
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::ostream;
class Player
{
public:
Player(const string& name = "") : m_Name(name), m_pNext(0) {}
string GetName() const {return m_Name;}
Player* GetNext() const {return m_pNext;}
void SetNext(Player* next) {m_pNext = next;}
private:
string m_Name;
Player* m_pNext; // pointer to the next player in list
};
class Lobby
{
friend ostream& operator<<(ostream& os, const Lobby& aLobby);
public:
Lobby(): m_pHead(0) {}
~Lobby() {Clear();}
void AddPlayer();
void RemovePlayer();
void Clear();
Player GetPlayer() const {return *m_pHead;}
Lobby(const Lobby& aLobby) // Copy Constructor
{
cout << "Copy Constructor Called...\n\n";
m_pHead = 0;
*m_pHead = aLobby.GetPlayer();
}
private:
Player* m_pHead;
};
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);
}
}
void Lobby::RemovePlayer()
{
if (m_pHead == 0)
{
cout << "The game lobby is empty. No one to remove!\n";
}
else
{
Player* pTemp = m_pHead;
m_pHead = m_pHead->GetNext();
delete pTemp;
}
}
void Lobby::Clear()
{
while (m_pHead != 0)
{
RemovePlayer();
}
}
ostream& operator<<(ostream& os, const Lobby& aLobby)
{
Player* pIter = aLobby.m_pHead;
os << "\nHere's who's in the game lobby:\n";
if (pIter == 0)
{
os << "The lobby is empty.\n";
}
else
{
while (pIter != 0)
{
os << pIter->GetName() << endl;
pIter = pIter->GetNext();
}
}
return os;
}
void testCopy(Lobby aLobby);
int main()
{
Lobby mLobby;
int choice;
do {
cout << mLobby;
cout << "\nGame Lobby\n";
cout << "0 - Exit the program.\n";
cout << "1 - Add a player to the lobby\n";
cout << "2 - Remove a player from the lobby.\n";
cout << "3 - Clear the lobby.\n";
cout << "4 - Copy the Lobby.\n";
cout << endl << "Enter choice: ";
cin >> choice;
switch(choice)
{
case 0: cout << "Good-Bye\n"; break;
case 1: mLobby.AddPlayer(); break;
case 2: mLobby.RemovePlayer(); break;
case 3: mLobby.Clear(); break;
case 4: testCopy(mLobby); break;
default: cout << "That was not a valid choice.\n";
}
} while(choice != 0);
return 0;
}
void testCopy(Lobby aLobby)
{
cout << "Copy Complete?\n\n";
}