Sams Teach Yourself C++ in 21 Days

(singke) #1
Line 11 begins the private section, which includes only the declaration on line 12 of the
private member variable itsAge. The class declaration ends with a closing brace and
semicolon on line 13.
Lines 17–20 contain the definition of the member function GetAge(). This method takes
no parameters, and it returns an integer. Note on line 17 that class methods include the
class name followed by two colons and the function name. 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 the same
as any other function.
The GetAge()function takes only one line; it returns the value in itsAge. Note that the
main()function cannot access itsAgebecause itsAgeis private to the Catclass. The
main()function has access to the public method GetAge().
Because GetAge()is a member function of the Catclass, it has full access to the itsAge
variable. This access enables GetAge()to return the value of itsAgeto main().
Line 25 contains the definition of the SetAge()member function. You can see that this
function takes one integer value, called age, and doesn’t return any values, as indicated
by void. SetAge()takes the value of the ageparameter and assigns it to itsAgeon line


  1. Because SetAge()is a member of the Catclass, it has direct access to the private
    member variable itsAge.
    Line 36 begins the definition, or implementation, of the Meow()method of the Catclass.
    It is a one-line function that prints the word “Meow” to the screen, followed by a new
    line. Remember that the \ncharacter prints a new line to the screen. You can see that
    Meowis set up just like the accessor functions in that it begins with the return type, the
    class name, the function name, and the parameters (none in this case).
    Line 43 begins the body of the program with the familiar main()function. On line 45,
    main()declares an object called Friskyof type Cat. Read a different way, you could say
    that main()declares a Catnamed Frisky.
    On line 46, the value 5 is assigned to the itsAgemember variable by way of the
    SetAge()accessor method. Note that the method is called by using the object name
    (Frisky) followed by the member operator (.) and the method name (SetAge()). In this
    same way, you can call any of the other methods in a class.


152 Day 6


NOTE The terms member functionand methodcan be used interchangeably.
Free download pdf