Book Image

Learning C++ by creating games with UE4

By : William Sherif
Book Image

Learning C++ by creating games with UE4

By: William Sherif

Overview of this book

Table of Contents (19 chapters)
Learning C++ by Creating Games with UE4
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
2
Variables and Memory
Index

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;  // inaccessible outside this class!
  ...