Testing Class GradeBook

Next, we’d like to use class GradeBook in a program. As you saw in Chapter 2, the function main (lines 19–23) begins the execution of every program.

In this program, we’d like to call class GradeBook’s displayMessage member function to display the welcome message. Typically, you cannot call a member function of a class until you create an object of that class. (As you’ll learn in Section 9.14, static member functions are an exception.) Line 21 creates an object of class GradeBook called myGradeBook. The variable’s type is GradeBook—the class we defined in lines 8–16. When we declare variables of type int, as we did in Chapter 2, the compiler knows what int is—it’s a fundamental type that’s “built into” C++. In line 21, however, the compiler does not automatically know what type GradeBook is—it’s a user-defined type. We tell the compiler what GradeBook is by including the class definition (lines 8–16). If we omitted these lines, the compiler would issue an error message. Each class you create becomes a new type that can be used to create objects. You can define new class types as needed; this is one reason why C++ is known as an extensible programming language.

Line 22 calls the member function displayMessage using variable myGradeBook followed by the dot operator (.), the function name displayMessage and an empty set of parentheses. This call causes the displayMessage function to perform its task. At the beginning of line 22, “myGradeBook.” indicates that main should use the GradeBook object that was created in line 21. The empty parentheses in line 12 indicate that member function displayMessage does not require additional data to perform its task, which is why we called this function with empty parentheses in line 22. (In Section 3.3, you’ll see how to pass data to a function.) When displayMessage completes its task, the program reaches the end of main (line 23) and terminates.

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

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