In Section 3.4, we introduced set functions for allowing clients of a class to modify the value of a private
data member. In Fig. 3.5, class GradeBook
defines member function setCourseName
to simply assign a value received in its parameter name
to data member courseName
. This member function does not ensure that the course name adheres to any particular format or follows any other rules regarding what a “valid” course name looks like. Suppose that a university can print student transcripts containing course names of only 25 characters or less. If the university uses a system containing GradeBook
objects to generate the transcripts, we might want class GradeBook
to ensure that its data member courseName
never contains more than 25 characters. The program of Figs. 3.15–3.17 enhances class GradeBook
’s member function setCourseName
to perform this validation (also known as validity checking).
1 // Fig. 3.15: GradeBook.h
2 // GradeBook class definition presents the public interface of
3 // the class. Member-function definitions appear in GradeBook.cpp.
4 #include <string> // program uses C++ standard string class
5
6 // GradeBook class definition
7 class GradeBook
8 {
9 public:
10 explicit GradeBook( std::string ); // constructor initialize courseName
11 void setCourseName( std::string ); // sets the course name
12 std::string getCourseName() const; // gets the course name
13 void displayMessage() const; // displays a welcome message
14 private:
15 std::string courseName; // course name for this GradeBook
16 }; // end class GradeBook