< previous page page_93 next page >

Page 93
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
46:     Cat Frisky;
47:     Frisky.SetAge(5);
48:     Frisky.Meow();
49:     cout << Frisky is a cat who is  ;
50:     cout << Frisky.GetAge() <<  years old.\n;
51:     Frisky.Meow();
52:     return 0;
53:  }

Output:
Meow.
Frisky is a cat who is 5 years old.
Meow.,
Analysis: Lines 614 contain the definition of the Cat class. Line 8 contains the keyword public, which tells the compiler that what follows is a set of public members. Line 9 has the declaration of the public accessor method GetAge(). GetAge() provides access to the private member variable itsAge, which is declared in line 13. Line 10 has the public accessor function SetAge(). SetAge() takes an integer as an argument and sets itsAge to the value of that argument.
Line 12 begins the private section, which includes only the declaration in line 13 of the private member variable itsAge. The class declaration ends with a closing brace and semicolon in line 14.
Lines 18 to 21 contain the definition of the member function GetAge(). This method takes no parameters; it returns an integer. Note that class methods include the class name followed by two colons and the function's name (line 18). This syntax tells the compiler that the GetAge() function you are defining here is the one that you declared in the Cat class. With the exception of this header line, the GetAge() function is created like any other function.
The GetAge() function takes only one line; it returns the value in itsAge. Note that the main() function cannot access itsAge because itsAge is private to the Cat class. The main() function has access to the public method GetAge(). Because GetAge() is a member function of the Cat class, it has full access to the itsAge variable. This access enables GetAge() to return the value of itsAge to main().
Line 26 contains the definition of the SetAge() member function. It takes an integer parameter and sets the value of itsAge to the value of that parameter in line 30. Because it is a member of the Cat class, SetAge() has direct access to the member variable itsAge.
Line 37 begins the definition, or implementation, of the Meow() method of the Cat class. It is a one-line function that prints the word Meow to the screen, followed by a new line. (Remember that the \n character prints a new line to the screen.)

 
< previous page page_93 next page >

If you like this book, buy it!