482 Day 14
(1)Circle (2)Rectangle (3)Square (0)Quit: 3
x x x x x
x x x x x
x x x x x
x x x x x
x x x x x
Abstract drawing mechanism!
(1)Circle (2)Rectangle (3)Square (0)Quit: 0
On lines 5–14, the abstract class Shapeis declared, with all three of its accessor
methods declared to be pure virtual. Note that this is not necessary, but is still a
good practice. If any one were declared pure virtual, the class would have been an
abstract class.
The GetArea()and GetPerim()methods are not implemented, but Draw()is imple-
mented in lines 16–19. Circleand Rectangleboth override Draw(), and both chain up
to the base method, taking advantage of shared functionality in the base class.
Complex Hierarchies of Abstraction ..............................................................
At times, you will derive abstract classes from other abstract classes. It might be that you
will want to make some of the derived pure virtual functions nonpure, and leave others
pure.
If you create the Animalclass, you can make Eat(),Sleep(),Move(), and Reproduce()
all be pure virtual functions. Perhaps from Animalyou derive Mammaland Fish.
On examination, you decide that every Mammalwill reproduce in the same way, and so
you make Mammal::Reproduce()nonpure, but you leave Eat(),Sleep(), and Move()as
pure virtual functions.
From Mammal, you derive Dog, and Dogmust override and implement the three remaining
pure virtual functions so that you can make objects of type Dog.
What you’ve said, as class designer, is that no Animals or Mammals can be instantiated,
but that all Mammals can inherit the provided Reproduce()method without overriding it.
Listing 14.10 illustrates this technique with a bare-bones implementation of these
classes.
LISTING14.10 Deriving Abstract Classes from Other Abstract Classes
0: // Listing 14.10
1: // Deriving Abstract Classes from other Abstract Classes
2: #include <iostream>
3: using namespace std;
ANALYSIS