Sams Teach Yourself C++ in 21 Days

(singke) #1
It is that last assessment that is of interest at the moment. A dog is a kind of canine, a
canine is a kind of mammal, and so forth. Taxonomists divide the world of living things
into Kingdom, Phylum, Class, Order, Family, Genus, and Species.
This specialization/generalization hierarchy establishes an is-arelationship. A Homo
sapiens (human) is a kind of primate. This relationship can be seen everywhere: A station
wagon is a kind of car, which is a kind of vehicle. A sundae is a kind of dessert, which is
a kind of food.
When something is said to be a kind of something else, it is implied that it is a special-
ization of that thing. That is, a car is a special kind of vehicle.

Inheritance and Derivation ............................................................................


The concept dog inherits—that is, it automatically gets—all the features of a mammal.
Because it is a mammal, you know that it moves and that it breathes air. All mammals,
by definition, move and breathe air. The concept of a dog adds the idea of barking, wag-
ging its tail, eating my revisions to this chapter just when I was finally done, barking
when I’m trying to sleep... Sorry. Where was I? Oh yes:
You can divide dogs into working dogs, sporting dogs, and terriers, and you can divide
sporting dogs into retrievers, spaniels, and so forth. Finally, each of these can be special-
ized further; for example, retrievers can be subdivided into Labradors and Goldens.
A Golden is a kind of retriever, which is a sporting dog, which is a dog, and thus a kind
of mammal, which is a kind of animal, and, therefore, a kind of living thing. This hierar-
chy is represented in Figure 12.1.
C++ attempts to represent these relationships by enabling you to define classes that
derive from one another. Derivation is a way of expressing the is-arelationship. You
derive a new class,Dog, from the class Mammal. You don’t have to state explicitly that
dogs move because they inherit that from Mammal.
A class that adds new functionality to an existing class is said to derive from that original
class. The original class is said to be the new class’s base class.
If the Dogclass derives from the Mammalclass, then Mammalis a base class of Dog.
Derived classes are supersets of their base classes. Just as dog adds certain features to the
idea of mammal, the Dogclass adds certain methods or data to the Mammalclass.
Typically, a base class has more than one derived class. Because dogs, cats, and horses
are all types of mammals, their classes would all derive from the Mammalclass.

372 Day 12

Free download pdf