< previous page page_252 next page >

Page 252
Private versus Protected
You may have noticed that a new access keyword, protected, has been introduced on lines 24 and 45 of Listing 16.1. Previously, class data had been declared private. However, private members are not available to derived classes. You could make itsAge and itsWeight public, but that is not desirable. You don't want other classes accessing these data members directly.
What you want is a designation that says, Make these visible to this class and to classes that derive from this class. That designation is protected. Protected data members and functions are fully visible to derived classes, but are otherwise private.
There are, in total, three access specifiers: public,protected, and private. If a function has an object of your class, it can access all the public member data and functions. The member functions, in turn, can access all private data members and functions of their own class and all protected data members and functions of any class from which they derive.
Therefore, the function Dog::WagTail() can access the private data itsBreed and can access the protected data in the Mammal class.
Even if other classes are layered between Mammal and Dog (for example, DomesticAnimals), the Dog class will still be able to access the protected members of Mammal, assuming that these other classes all use public inheritance.
Listing 16.2 demonstrates how to create objects of type Dog and access the data and functions of that type.
LISTING 16.2 USING A DERIVED OBJECT

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 1:    //Listing 16.2 Using a derived object
 2:
 3:    #include <iostream.h>
 4:    enum BREED { YORKIE, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB };
 5:
 6:    class Mammal
 7:    {
 8:    public:
 9:      // constructors
10:      Mammal():itsAge(2), itsWeight(5){}
11:      ~Mammal(){}
12:
13:      //accessors
14:      int GetAge()const { return itsAge; }
15:      void SetAge(int age) { itsAge = age; }
16:      int GetWeight() const { return itsWeight; }
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
continues

 
< previous page page_252 next page >

If you like this book, buy it!