Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Object-Oriented Programming 151

6


22: // definition of SetAge, public
23: // accessor function
24: // sets itsAge member
25: void Cat::SetAge(int age)
26: {
27: // set member variable itsAge to
28: // value passed in by parameter age
29: itsAge = age;
30: }
31:
32: // definition of Meow method
33: // returns: void
34: // parameters: None
35: // action: Prints “meow” to screen
36: void Cat::Meow()
37: {
38: std::cout << “Meow.\n”;
39: }
40:
41: // create a cat, set its age, have it
42: // meow, tell us its age, then meow again.
43: int main()
44: {
45: Cat Frisky;
46: Frisky.SetAge(5);
47: Frisky.Meow();
48: std::cout << “Frisky is a cat who is “ ;
49: std::cout << Frisky.GetAge() << “ years old.\n”;
50: Frisky.Meow();
51: return 0;
52: }

Meow.
Frisky is a cat who is 5 years old.
Meow.
Lines 5–13 contain the definition of the Catclass. Line 7 contains the keyword
public, which tells the compiler that what follows is a set of public members.
Line 8 has the declaration of the public accessor method GetAge(). GetAge()provides
access to the private member variable itsAge, which is declared on line 12. Line 9 has
the public accessor functionSetAge(). SetAge()takes an integer as an argument and
sets itsAgeto the value of that argument.
Line 10 has the declaration of the class method Meow().Meow()is not an accessor func-
tion. Here it is a general method that prints the word “Meow” to the screen.

OUTPUT


LISTING6.3 continued


ANALYSIS
Free download pdf