GradeBook.cpp: Defining Member Functions in a Separate Source-Code File

Source-code file GradeBook.cpp (Fig. 3.12) defines class GradeBook’s member functions, which were declared in lines 11–14 of Fig. 3.11. The definitions appear in lines 9–33 and are nearly identical to the member-function definitions in lines 11–35 of Fig. 3.9. Note that the const keyword must appear in both the function prototypes (Fig. 3.11, lines13–14) and the function definitions for functions getCourseName and displayMessage (lines 22 and 28).

Each member-function name (lines 9, 16, 22 and 28) is preceded by the class name and ::, which is known as the scope resolution operator. This “ties” each member function to the (now separate) GradeBook class definition (Fig. 3.11), which declares the class’s member functions and data members. Without “GradeBook::” preceding each function name, these functions would not be recognized by the compiler as member functions of class GradeBook—the compiler would consider them “free” or “loose” functions, like main. These are also called global functions. Such functions cannot access GradeBook’s private data or call the class’s member functions, without specifying an object. So, the compiler would not be able to compile these functions. For example, lines 18 and 24 in Fig. 3.12 that access variable courseName would cause compilation errors because courseName is not declared as a local variable in each function—the compiler would not know that courseName is already declared as a data member of class GradeBook.


Image Common Programming Error 3.3

When defining a class’s member functions outside that class, omitting the class name and scope resolution operator (::) preceding the function names causes errors.


To indicate that the member functions in GradeBook.cpp are part of class GradeBook, we must first include the GradeBook.h header (line 5 of Fig. 3.12). This allows us to access the class name GradeBook in the GradeBook.cpp file. When compiling GradeBook.cpp, the compiler uses the information in GradeBook.h to ensure that

1. the first line of each member function (lines 9, 16, 22 and 28) matches its prototype in the GradeBook.h file—for example, the compiler ensures that getCourseName accepts no parameters and returns a string, and that

2. each member function knows about the class’s data members and other member functions—for example, lines 18 and 24 can access variable courseName because it’s declared in GradeBook.h as a data member of class GradeBook, and line 31 can call function getCourseName, because it’s declared as a member function of the class in GradeBook.h (and because the call conforms with the corresponding prototype).

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

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