Chapter 24. Do Not Disturb: Protected Members

In This Chapter

  • Protecting members of a class

  • Why do that?

  • Declaring friends of the class

My goal with this part of the book, starting with Chapter 21, has been to model real-world objects in C++ using the class structure. In Chapter 22, I introduce the concept of member functions in order to assign classes' active properties. Returning to the microwave oven example in Chapter 21, assigning active properties allows me to give my Oven class properties like cook() and defrost().

However, that's only part of the story. I still haven't put a box around the insides of my classes. I can't very well hold someone responsible if the microwave catches on fire as long as the insides are exposed to anyone who wants to mess with them.

This chapter "puts a box" around the classes by declaring certain members off limits to user functions.

Protecting Members

Members of a class can be flagged as inaccessible from outside the class with the keyword protected. This is in direct opposition to the public keyword, which designates those members that are accessible to all functions. The public members of a class form the interface to the class (think of the keypad on the front of the microwave oven) while the protected members form the inner workings.

Note

There is a third category called private. The only difference between private and protected members is the way they react to inheritance, which I don't present until Chapter 28.

Why you need protected members

Declaring ...

Get Beginning Programming with C++ For Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.