In This Chapter
Declaring members protected
Accessing protected members from within the class
Accessing protected members from outside the class
Chapter 12 introduces the concept of the class. That chapter describes the
public keyword as though it were part of the class declaration — just something you do. In this chapter, you find out about an alternative to
The members of a class can be marked protected, which makes them inaccessible outside the class. The alternative is to make the members public. Public members are accessible to all.
Please understand the term inaccessible in a weak sense. Any programmer can go into the source code, remove the
protected keyword, and do whatever she wants. Further, any hacker worth his salt can code into a protected section of code. The
protected keyword is designed to protect a programmer from herself by preventing inadvertent access.
To understand the role of protected, think about the goals of object-oriented programming:
To protect the internals of the class from outside functions. Suppose, for example, that you have a plan to build a software microwave (or whatever), provide it with a simple interface to the outside world, and then put a box around it to keep others from messing with the insides. The protected keyword is that box.
To make the class responsible for maintaining its internal state. It's not fair to ask the class to be responsible ...