Sams Teach Yourself C++ in 21 Days

(singke) #1
40: // value passed in by parameter age
41: itsAge = age;
42: }
43:
44: // definition of Meow method
45: // returns: void
46: // parameters: None
47: // action: Prints “meow” to screen
48: void Cat::Meow()
49: {
50: std::cout << “Meow.\n”;
51: }
52:
53: // create a cat, set its age, have it
54: // meow, tell us its age, then meow again.
55: int main()
56: {
57: Cat Frisky(5);
58: Frisky.Meow();
59: std::cout << “Frisky is a cat who is “ ;
60: std::cout << Frisky.GetAge() << “ years old.\n”;
61: Frisky.Meow();
62: Frisky.SetAge(7);
63: std::cout << “Now Frisky is “ ;
64: std::cout << Frisky.GetAge() << “ years old.\n”;
65: return 0;
66: }

Meow.
Frisky is a cat who is 5 years old.
Meow.
Now Frisky is 7 years old.
Listing 6.4 is similar to Listing 6.3, 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
value—not even void.
Lines 19–22 show the implementation of the constructor. It is similar to the implementa-
tion of the SetAge()accessor function. As you can see, the class name precedes the con-
structor name. As mentioned before, this identifies the method,Cat()in this case as a
part of the Catclass. This is a constructor, so there is no return value—not even void.
This constructor does, however, take an initial value that is assigned to the data member,
itsAge, on line 21.

OUTPUT


156 Day 6


LISTING6.4 continued

ANALYSIS
Free download pdf