< previous page page_97 next page >

Page 97
LISTING 6.2 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
59:    Frisky.Meow();
60:    cout << Frisky is a cat who is  ;
61:    cout << Frisky.GetAge() <<  years old.\n;
62:    Frisky.Meow();
63:    Frisky.SetAge(7);
64:    cout << Now Frisky is  ;
65:    cout << Frisky.GetAge() <<  years old.\n;
66:    return 0;
67:  }

Output:
Meow,
Frisky is a cat who is 5 years old.
Meow.
Now Frisky is 7 years old.
Analysis: Listing 6.2 is similar to 6.1, except that line 9 adds a constructor that takes an integer. Line 10 declares the destructor, which takes no parameters. Destructors never take parameters, and neither constructors nor destructors return a valuenot even void.
Lines 1922 show the implementation of the constructor, which is similar to the implementation of the SetAge() accessor function. There is no return value.
Lines 2426 show the implementation of the destructor ~Cat(). This function does nothing, but you must include the definition of the function if you declare it in the class declaration.
Line 58 contains the definition of a Cat object, Frisky. The value 5 is passed in to Frisky's constructor. There is no need to call SetAge(), because Frisky was created with the value 5 in its member variable itsAge, as shown in line 61. In line 63, Frisky's itsAge variable is reassigned to 7. Line 65 prints the new value.
Summary
In this hour you learned how to create new data types called classes. You learned how to define variables of these new types, which are called objects.
A class has data members, which are variables of various types, including other classes. A class also includes member functions, also known as methods. You use these member functions to manipulate the member data and to perform other services.
Class membersboth data and functionscan be public or private. Public members are accessible to any part of your program. Private members are accessible only to the member functions of the class.

 
< previous page page_97 next page >

If you like this book, buy it!