Sams Teach Yourself C++ in 21 Days

(singke) #1
To keep the program reasonably simple and manageable, only six methods have been put
in the Mammalclass—four accessor methods,Speak(), and Sleep().
The Dogclass inherits from Mammal, as indicated on line 30. You know Doginherits from
Mammalbecause of the colon following the class name (Dog), which is then followed by
the base class name (Mammal).
Every Dogobject will have three member variables:itsAge,itsWeight, and itsBreed.
Note that the class declaration for Dogdoes not include the member variables itsAgeand
itsWeight. Dog objects inherit these variables from the Mammalclass, along with all
Mammal’s methods except the copy operator and the constructors and destructor.

Private Versus Protected ......................................................................................


You might have noticed that a new access keyword,protected, has been introduced on
lines 25 and 46 of Listing 12.1. Previously, class data had been declared private.
However, private members are not available outside of the existing class. This privacy
even applies to prevent access from derived classes. You could make itsAgeand
itsWeightpublic, but that is not desirable. You don’t want other classes accessing these
data members directly.

376 Day 12


There is an argument to be made that you ought to make all member data
private and never protected. Stroustrup (the creator of C++) makes this
argument in The Design and Evolution of C++, ISBN 0-201-543330-3, Addison
Wesley, 1994. Protected methods, however, are not generally regarded as
problematic, and can be very useful.

NOTE

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.
In total, three access specifiers exist: 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.
Thus, the function Dog::WagTail()can access the private data itsBreedand can access
the protected data of itsAgeand itsWeightin the Mammalclass.
Even if other classes are layered between Mammaland Dog(for example,
DomesticAnimals), the Dogclass will still be able to access the protected members of
Free download pdf