Game Development Reference
In-Depth Information
When using public access, this line of code is allowed, which is why our program compiled without
errors in Chapter 7. We could fix the compile error by changing our class to code shown in Listing 8-3.
Listing 8-3. A
public
Class
class Player
{
public:
std::string m_name;
};
There is a problem caused by having public member variables in C++: It breaks our encapsulation.
We might decide later to separate the player's first name and surname into separate strings, for
example, and then code that relies on our
Player
class supplying a single name would break. The
proper way to fix the problem is to provide accessor methods. Listing 8-4 shows the
Player
class
with accessors for the
name
variable.
Listing 8-4. A
Player Class
with Accessors
class Player
{
private:
std::string m_name;
public:
void SetName(const std::string& name)
{
m_name = name;
}
const std::string& GetName() const
{
return m_name;
}
};
You now have a class that respects the rules of encapsulation. The code that refused to compile
earlier can now be fixed using the following code.
string name;
cin >> name;
player.SetName(name);
This section has shown why you would use classes in C++ and how to create a basic class that
uses the benefits of encapsulation. To recap, the
public
specifier tells the compiler that any of the
following member variables and methods are accessible to code outside of the class. The
private
access specifier informs the compiler that the following member variables and methods are only
accessible from inside the class; that is, from within
public
or
private
methods that make up the
class. The rest of this chapter looks at how we use classes properly in our code base.