Skip to main content

Section 19.4 Protected Access

Another way we can allow Student to work with the Person it has inherited from is to use the protected access modifier. protected members are accessible within the class itself and by any derived classes. They are treated as private elsewhere.
To use protected in our code, we would change the member variables of Person to be protected instead of private. That would allow Student to access m_name and m_age directly.
Listing 19.4.1.
Try uncommenting the last line to verify that main does not have access to the private members of Person. protected only allows access within other classes that derive from Person. The assumption here is that anyone extending Person likely needs to understand the internals of Person and so should be trusted to access the members directly.
Table 19.4.2. Access Modifiers
Modifier Meaning
private
Only accessible within this class (not just the same object).
protected
Accessible within this class and any derived classes.
public
Accessible from anywhere.
There is some merit to continuing to use private for member variables. Doing so will prevent derived classes from being tightly coupled with the implementation of the base class. Maintaining separation between the two can make it easier to change base class code without breaking derived classes. However, it can also lead to more boilerplate code, as you have to provide public getter and setter functions for derived classes to access the member variables.
You also can have private variables and protected getters/setters if you want to allow derived classes to have special access to some of the base class data but do not want other code to be able to use even the getters or setters.

Insight 19.4.1.

Deciding whether to use protected or private for member variables is a design decision. If you are designing a class that you expect to be extended, and you want to allow derived classes to access certain members, then protected is appropriate. If you want to keep the implementation details hidden from derived classes, then private is the way to go.
In this book, we will use protected for member variables in base classes that we expect to be extended to avoid cluttering things up with getters and setters for those variables. In a large codebase shared by many different programmers we might make a different design decision.

Checkpoint 19.4.1.

You have attempted of activities on this page.