protected
class members in C++, including how and when to use them in your code, especially in the context of inheritance and class designIn our earlier lesson on encapsulation, we saw how we can (and should) make some of the variables and functions of our class private
.
This hides those functions and variables from the outside world. This makes our systems easier to design and use.
For example, we can create objects that allow the outside world to see our character’s health, but not change it:
class Character {
public:
int GetHealth() { return mHealth; }
private:
int mHealth { 100 };
};
An interesting problem arises when we’re using inheritance in this context. Specifically, code in a derived class also can’t access any inherited private members.
Below, we have a new class that inherits from Character
, but this code also can’t access the private mHealth
variable:
class Character {
public:
int GetHealth() { return mHealth; }
private:
int mHealth { 100 };
};
class Healer : public Character {
public:
void Heal(int Amount) { mHealth += Amount; }
};
error: 'Character::mHealth': cannot access private
member declared in class 'Character'
protected
MembersFortunately, we 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 code in child classes.
Below, we’ve changed mHealth
to be protected
rather than private
:
#include <iostream>
using namespace std;
class Character {
public:
int GetHealth(){ return mHealth; }
protected:
int mHealth{100};
};
class Healer : public Character {
public:
void Heal(int Amount){ mHealth += Amount; }
};
int main(){
Healer Player;
cout << "Health: " << Player.GetHealth();
Player.Heal(50);
cout << "\nHealth: " << Player.GetHealth();
}
Health: 100
Health: 150
What are the three access specifiers we have for classes?
What is the difference between protected
and private
access?
We’ve now covered the three access levels we have in C++:
private
members are only accessible within the same class they are definedprotected
members are accessible within the same class, and any sub-classpublic
members are accessible from anywhereIn the next lesson, we'll delve into Member Initializer Lists. Here's what we’ll learn:
Learn about protected
class members in C++, including how and when to use them in your code, especially in the context of inheritance and class design
Become a software engineer with C++. Starting from the basics, we guide you step by step along the way