C++ For Dummies by Davis Stephen R

C++ For Dummies by Davis Stephen R

Author:Davis , Stephen R.
Language: eng
Format: epub
ISBN: 9781118823835
Publisher: Wiley
Published: 2014-05-16T13:53:39+00:00


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

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

double grade() { return gpa; }

// here we allow the grade to be changed

double grade(double newGPA)

{

double 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

double gpa;

};

The addition of the member function grade(double) allows the application to set the gpa. Notice, however, that the class still hasn’t given up control completely. The application can’t set gpa to any old value; only a gpa in the legal range of values (from 0 through 4.0) is accepted.

Thus, the Student class has provided access to an internal data member without abdicating its responsibility to make sure that the internal state of the class is valid.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.