Member Functions setCourseName and getCourseName

Member function setCourseName (lines 14–17) does not return any data when it completes its task, so its return type is void. The member function receives one parameter—name—which represents the course name that will be passed to it as an argument (as we’ll see in line 50 of main). Line 16 assigns name to data member courseName, thus modifying the object—for this reason, we do not declare setCourseName const. In this example, setCourseName does not validate the course name—i.e., the function does not check that the course name adheres to any particular format or follows any other rules regarding what a “valid” course name looks like. Suppose, for instance, that a university can print student transcripts containing course names of only 25 characters or fewer. In this case, we might want class GradeBook to ensure that its data member courseName never contains more than 25 characters. We discuss validation in Section 3.8.

Member function getCourseName (lines 20–23) returns a particular GradeBook object’s courseName, without modifying the object—for this reason, we declare getCourseName const. The member function has an empty parameter list, so it does not require additional data to perform its task. The function specifies that it returns a string. When a function that specifies a return type other than void is called and completes its task, the function uses a return statement (as in line 22) to return a result to its calling function. For example, when you go to an automated teller machine (ATM) and request your account balance, you expect the ATM to give you a value that represents your balance. Similarly, when a statement calls member function getCourseName on a GradeBook object, the statement expects to receive the GradeBook’s course name (in this case, a string, as specified by the function’s return type).

If you have a function square that returns the square of its argument, the statement

result = square( 2 );

returns 4 from function square and assigns to variable result the value 4. If you have a function maximum that returns the largest of three integer arguments, the statement

biggest = maximum( 27, 114, 51 );

returns 114 from function maximum and assigns this value to variable biggest.

The statements in lines 16 and 22 each use variable courseName (line 34) even though it was not declared in any of the member functions. We can do this because courseName is a data member of the class and data members are accessible from a class’s member functions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.228