Getters and setters
You might have noticed that once we slap private
onto the Player
class definition, we can no longer read or write the name of the player from outside the Player
class.
If we try and read the name with the following code:
Player me; cout << me.name << endl;
Or write to the name, as follows:
me.name = "William";
Using the struct Player
definition with private
members, we will get the following error:
main.cpp(24) : error C2248: 'Player::name' : cannot access private member declared in class 'Player'
This is just what we asked for when we labeled the name
field private
. We made it completely inaccessible outside the Player
class.
Getters
A getter (also known as an accessor function) is used to pass back copies of internal data members to the caller. To read the player's name, we'd deck out the Player
class with a member function specifically to retrieve a copy of that private
data member:
class Player { private: string name;...