Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C++ For Dummies (2004) [eng].pdf
Скачиваний:
84
Добавлен:
16.08.2013
Размер:
8.09 Mб
Скачать

Chapter 15

Protecting Members:

Do Not Disturb

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 public.

Protecting Members

The members of a class can be marked protected, which makes them inac­ cessible 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 what­ ever she wants. Further, any hacker worth his salt can code into a protected section of code. The protected keyword is designed to protect a program­ mer from herself by preventing inadvertent access.

Why you need protected members

To understand the role of protected, think about the goals of object-oriented programming:

202 Part III: Introduction to Classes

To protect the internals of the class from outside functions. Suppose, for example, that you have a plan to build a software microwave (or what­ ever), 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 if others can reach in and manipu­ late its internals (any more than it’s fair to ask a microwave designer to be responsible for the consequences of my mucking with a microwave’s internal wiring).

To limit the interface of the class to the outside world. It’s easier to figure out and use a class that has a limited interface (the public mem­ bers). Protected members are hidden from the user and need not be learned. The interface becomes the class; this is called abstraction (see Chapter 11 for more on abstraction).

To reduce the level of interconnection between the class and other code. By limiting interconnection, you can more easily replace one class with another or use the class in other programs.

Now, I know what you functional types out there are saying: “You don’t need some fancy feature to do all that. Just make a rule that says certain members are publicly accessible, and others are not.”

Although that is true in theory, it doesn’t work. People start out with all kinds of good intentions, but as long as the language doesn’t at least discourage direct access of protected members, these good intentions get crushed under the pressure to get the product out the door.

Discovering how protected members work

Adding the keyword public to a class makes subsequent members public, which means that they are accessible by non-member functions. Adding the keyword protected makes subsequent members of the class protected, which means they are not accessible by non-members of the class. You can switch between public and protected as often as you like.

Suppose you have a class named Student. In this example, the following capabilities are all that a fully functional, upstanding Student needs (notice the absence of spendMoney() and drinkBeer() — this is a highly stylized student):

addCourse(inthours, float grade) — adds a course

grade() — returns the current grade point average

hours() — returns the number of hours earned toward graduation

Chapter 15: Protecting Members: Do Not Disturb 203

The remaining members of Student can be declared protected to keep other functions’ prying expressions out of Student’s business.

class Student

{

public:

//grade - return the current grade point average float grade()

{

return gpa;

}

//hours - return the number of semester hours int hours()

{

return semesterHours;

}

//addCourse - add another course to the student’s record float addCourse(int hours, float grade);

//the following members are off-limits to others protected:

int semesterHours; // hours earned toward graduation

float gpa;

// grade point average

};

Now the members semester hours and gpa are accessible only to other members of Student. Thus, the following doesn’t work:

Student s;

int main(int argcs, char* pArgs[])

{

//raise my grade (don’t make it too high; otherwise, no

//one would believe it)

s.gpa = 3.5;

//

<- generates compiler error

float gpa = s.grade(); //

<- this public function reads

 

//

a copy of the value, but you

return 0;

// can’t change it from here

 

 

}

The application’s attempt to change the value of gpa is flagged with a com­ piler error.

It’s considered good form not to rely on the default and specify either public or private at the beginning of the class. Most of the time, people start with the public members because they make up the interface of the class. Protected members are saved until later.

204 Part III: Introduction to Classes

A class member can also be protected by declaring it private. In this book, I use the protected keyword exclusively since it expresses the more generic concept.

Making an Argument for Using

Protected Members

Now that you know a little more about how to use protected members in an actual class, I can replay the arguments for using protected members.

Protecting the internal state of the class

Making the gpa member protected precludes the application from setting the grade point average to some arbitrary value. The application can add courses, but it can’t change the grade point average.

If the application has a legitimate need to set the grade point average directly, the class can provide a member function for that purpose, as follows:

class Student

{

public:

//same as before float grade()

{

return gpa;

}

//here we allow the grade to be changed float grade(float newGPA)

{

float oldGPA = gpa;

//only if the new value is valid if (newGPA > 0 && newGPA <= 4.0)

{

gpa = newGPA;

}

return oldGPA;

}

// ...other stuff is the same including the data members: protected:

int semesterHours; // hours earned toward graduation float gpa;

};