Game Development Reference
In-Depth Information
Whether you add default constructors to your classes will depend on whether it is valid to do so.
Not all classes make sense when they are not passed values to initialize them. Class constructors
are called when objects of our class type are being created; class destructors are called when our
objects are being destroyed. Objects can be destroyed in a number of ways, but our code currently
only destroys objects when they are going out of scope . Listing 8-7 shows an example.
Listing 8-7. Going out of Scope
int _tmain(int argc, _TCHAR* argv[])
{
Player player;
GameLoop::WelcomePlayer(player);
bool isPlaying = true;
while (isPlaying)
{
isPlaying = GameLoop::RunGame();
}
return 0;
}
The Player constructor is called when the player variable is created. This code is calling the default
constructor. The player variable goes out of scope once the function that contains it returns. This
means that the destructor is called automatically after the return call is executed. Listing 8-8 shows
the Player class with a destructor added.
Listing 8-8. The Player Class destructor
class Player
{
private:
std::string m_name;
public:
Player()
{
}
Player(const std::string& name)
: m_name(name)
{
}
~Player()
{
}
void SetName(const std::string& name)
{
m_name = name;
}
 
Search WWH ::




Custom Search