|
|
|
|
|
|
|
through any object of the class. This distinction is both important and confusing. To make it a bit clearer, consider an example from earlier in this chapter: |
|
|
|
|
|
|
|
|
class Cat
{
unsigned int itsAge;
unsigned int itsWeight;
Meow();
}; |
|
|
|
|
|
|
|
|
In this declaration, itsAge, itsWeight, and Meow() are all private, because all members of a class are private by default. This means that unless you specify otherwise, they are private. |
|
|
|
|
|
|
|
|
Cat Boots;
Boots.itsAge=5; // error! can't access private data! |
|
|
|
|
|
|
|
|
the compiler flags this as an error. In effect, you've said to the compiler, I'll access itsAge, itsWeight, and Meow() from only within member functions of the Cat class. Yet here you've accessed it from outside a Cat method. Just because Boots is an object of class Cat, that doesn't mean that you can access the parts of Boots that are private. |
|
|
|
|
|
|
|
|
The way to use Cat so that you can access the data members is to declare a section of the Cat declaration to be public: |
|
|
|
|
|
|
|
|
class Cat
{
public:
unsigned int itsAge;
unsigned int itsWeight;
Meow();
}; |
|
|
|
|
|
|
|
|
Now itsAge, itsWeight, and Meow() are all public. Boots.itsAge=5 compiles without a problem. |
|
|
|
|
|
|
|
|
New Term: As a general rule of design, you should keep the member data of a class private. Therefore, you must create public functions known as accessor 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. |
|
|
|
|
|
|
|
|
Accessor functions enable you to separate the details of how the data is stored from how it is used. This enables you to change how the data is stored without having to rewrite functions that use the data. |
|
|
|
|
|