Sams Teach Yourself C++ in 21 Days

(singke) #1
9: void SetAge(unsigned int Age);
10:
11: unsigned int GetWeight();
12: void SetWeight(unsigned int Weight);
13:
14: // public member functions
15: void Meow();
16:
17: // private member data
18: private:
19: unsigned int itsAge;
20: unsigned int itsWeight;
21: };

This class has five public methods. Lines 8 and 9 contain the accessor methods
for itsAge. You can see that on line 8 there is a method for getting the age and
on line 9 there is one for setting it. Lines 11 and 12 contain similar accessor methods for
itsWeight. These accessor functions set the member variables and return their values.
The public member function Meow()is declared on line 15. Meow()is not an accessor
function. It doesn’t get or set a member variable; it performs another service for the
class, printing the word “Meow.”
The member variables themselves are declared on lines 19 and 20.
To set Frisky’s age, you would pass the value to the SetAge()method, as in
Cat Frisky;
Frisky.SetAge(5); // set Frisky’s age using the public accessor
Later today, you’ll see the specific code for making the SetAgeand the other methods
work.
Declaring methods or data private enables the compiler to find programming mistakes
before they become bugs. Any programmer worth his consulting fees can find a way
around privacy if he wants to. Stroustrup, the inventor of C++, said, “The C++ access
control mechanisms provide protection against accident—not against fraud” (ARM,
1990).

148 Day 6


LISTING6.2 continued

ANALYSIS

The classKeyword
Syntax for the classkeyword is as follows:
class class_name
{
Free download pdf