Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Object-Oriented Programming 147

6


To access private data in a class, you must create public functions known as accessor
methods. Use these methods to set and get the private member variables. These accessor
methods are the member functions that other parts of your program call to get and set
your private member variables.
A public accessor method is a class member function used either to read (get) the value
of a private class member variable or to set its value.
Why bother with this extra level of indirect access? Why add extra functions when it is
simpler and easier to use the data directly? Why work through accessor functions?
The answer to these questions is that accessor functions enable you to separate the
details of how the data is storedfrom how it is used. By using accessor functions, you
can later change how the data is stored without having to rewrite any of the other func-
tions in your programs that use the data.
If a function that needs to know a Cat’s age accesses itsAgedirectly, that function would
need to be rewritten if you, as the author of the Catclass, decided to change how that
data is stored. By having the function call GetAge(), your Catclass can easily return the
right value no matter how you arrive at the age. The calling function doesn’t need to
know whether you are storing it as an unsignedinteger or a long, or whether you are
computing it as needed.
This technique makes your program easier to maintain. It gives your code a longer life
because design changes don’t make your program obsolete.
In addition, accessor functions can include additional logic, for instance, if a Cat’s age is
unlikely to be more than 100, or its weight is unlikely to be 1000. These values should
probably not be allowed. An accessor function can enforce these types of restrictions as
well as do other tasks.
Listing 6.2 shows the Catclass modified to include private member data and public
accessor methods. Note that this is not a listing that can be run if it is compiled.

LISTING6.2 A Class with Accessor Methods


1: // Cat class declaration
2: // Data members are private, public accessor methods
3: // mediate setting and getting the values of the private data
4:
4: class Cat
5: {
6: public:
7: // public accessors
8: unsigned int GetAge();
Free download pdf