Game Development Reference
In-Depth Information
Listing 8-1. The
Player
Class
#pragma once
#include <string>
class Player
{
std::string m_name;
};
The
Player
class in Listing 8-1 might look familiar. It is almost exactly the same as the
Player struct
from Listing 7-6. All we have done is change the
struct
keyword to the
class
keyword. If you were
to do this in our Text Adventure example from the previous chapter, the code would no longer
compile. When you try to compile in Visual Studio you receive the following error:
Error 1 error C2248: 'Player::m_name' : cannot access private member declared in class 'Player'
This error occurs thanks to the encapsulation features of C++. Listing 8-2 shows why this is the case.
Listing 8-2.
class
vs.
struct
Encapsulation
class Player
{
private:
std::string m_name;
};
struct Player
{
public:
std::string m_name;
};
The code in Listing 8-2 makes the distinction between a class and a struct in C++ explicit. By default all
member variables and functions in a class are private. In a struct all members and methods are public.
Note
A traditional C style struct cannot contain any methods (member functions). However, these are
allowed in C++, which means that the difference between a class and a struct in C++ is simply the default
access to member variables and functions.
The error thrown by the compiler is caused by the following line of code:
cin >> player.m_name;