Game Development Reference
In-Depth Information
Any code that you could place inside these methods would be identical and all of the data contained
by both would also be the same. The major difference between the two methods is the length of time
it takes to execute the two. Passing player by value would invoke the copy constructor, whereas
passing a constant reference does not. Using a constant reference therefore avoids the time taken to
call the copy constructor method and the length of time it takes to execute a full copy of the class.
Passing by a constant reference also helps protect programmers against another more subtle
problem. The first method has passed the class by value and therefore the player parameter is a
copy of the original object. If you then called any methods that set values on the parameter, that data
would be lost when the function returns. You can get around this by declaring the copied object as
const ; however, at that point there's no reason why you wouldn't also use a reference. Using const
variables with copied objects will cause the compiler to throw errors if you try to call public methods
on the object, which helps to avoid a source of errors and bugs in your games.
Assignment Operators
Although copy constructors will be invoked when passing objects by value into functions or
methods, assignment operators are invoked when using the = operator on objects. Listing 12-3
shows how you can overload an assignment operator on the Player class.
Listing 12-3. The Player Assignment Operator
class Player
: public Entity
{
private:
const Room* m_pCurrentRoom;
std::string m_name;
public:
Player()
{
}
Player(const Player& originalPlayer)
{
m_pCurrentRoom = originalPlayer.m_pCurrentRoom;
m_name = originalPlayer.m_name;
}
Player& operator=(const Player& originalPlayer)
{
m_pCurrentRoom = originalPlayer.m_pCurrentRoom;
m_name = originalPlayer.m_name;
return *this;
}
 
Search WWH ::




Custom Search