We have previously seen how we can (and should) make some of the variables and functions of our class private
, to prevent code from outside of our class accessing them.
class Character {
private:
int Health { 100 };
};
The following code will not compile, as private
members cannot be accessed from outside the Character
class:
class Monster : public Character {
public:
int GetHealth() { return Health; }
};
We could make Health
public again, but we've already seen why that can be problematic. But equally, child classes are inherently linked to their parent. Locking them out from accessing large parts of the parent class can be quite restrictive.
Fortunately, we do have an access level between public
and private
that solves this problem. This access level is called protected
.
protected
members cannot be accessed by functions that exist outside our class hierarchy, but they can still be accessed by child classes. This is exactly what we need to solve our problem:
class Character {
protected:
int Health { 100 };
};
class Monster : public Character {
public:
void GetHealth() { return Health; }
};
To summarise:
private
members are only accessible within that same classprotected
members are accessible within that same class, and any sub classpublic
members are accessible to any codeWhat are the three access specifiers we have for classes?
What is the difference between protected
and private
access?
Become a software engineer with C++. Starting from the basics, we guide you step by step along the way