Protected Class Members
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
In our earlier lesson on encapsulation, we saw how we can (and should) make some of the variables and functions of our class private
.
Encapsulation and Access Specifiers
A guide to encapsulation, class invariants, and controlling data access with public
and private
specifiers.
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 };
};
Access Restriction with Inheritance
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'
Using protected
Members
Fortunately, 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
Test your Knowledge
Access Modifiers
What are the three access specifiers we have for classes?
What is the difference between protected
and private
access?
Summary
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 anywhere
Member Initializer Lists
This lesson introduces Member Initializer Lists, focusing on their advantages for performance and readability, and how to use them effectively