Game Development Reference
In-Depth Information
Player(const Player& originalPlayer)
{
m_pCurrentRoom = originalPlayer.m_pCurrentRoom;
m_name = originalPlayer.m_name;
}
void SetName(const std::string& name)
{
m_name = name;
}
const std::string& GetName() const
{
return m_name;
}
void SetCurrentRoom(const Room* pCurrentRoom)
{
m_pCurrentRoom = pCurrentRoom;
}
const Room* GetCurrentRoom() const
{
return m_pCurrentRoom;
}
};
The copy constructor in Listing 12-1 is a constructor method that takes a constant reference to an
object of the same type of class; in this case the Player copy constructor takes a constant reference
to another Player object. Copy constructors are an added cost when passing objects into functions.
Usually you would be better served by passing a constant reference into the function instead. Copy
constructors are mostly useful when you wish to return a new instance of an object from a function.
When you do this, the object you are returning will go out of scope and be destroyed after the
function has returned. Returning objects by value ensures that you are not exposed to bugs caused
by trying to return references to local variables that no longer exist. Listing 12-2 shows two different
functions that take a player by value and by constant reference.
Listing 12-2. Passing by Value and const Reference
void CopyPlayer(Player player)
{
}
void PassPlayerByConstReference(const Player& player)
{
}
 
Search WWH ::




Custom Search