Polymorphism 477
14
Squarederives from Rectanglein lines 64–71, and it, too, overrides the GetPerim()
method, inheriting the rest of the methods defined in Rectangle.
It is troubling, though, that a client might try to instantiate a Shape, and it might be desir-
able to make that impossible. After all, the Shapeclass exists only to provide an interface
for the classes derived from it; as such, it is an abstract data type, or ADT.
In an abstract class, the interface represents a concept (such as shape) rather than a spe-
cific object (such as circle). In C++, an abstract class is always the base class to other
classes, and it is not valid to make an instance of an abstract class.
Pure Virtual Functions ....................................................................................
C++ supports the creation of abstract classes by providing the pure virtual function. A
virtual function is made pure by initializing it with zero, as in
virtual void Draw() = 0;
In this example, the class has a Draw()function, but it has a null implementation and
cannot be called. It can, however, be overwritten within descendant classes.
Any class with one or more pure virtual functions is an abstract class, and it becomes
illegal to instantiate. In fact, it is illegal to instantiate an object of any class that is an
abstract class or any class that inherits from an abstract class and doesn’t implement all
of the pure virtual functions. Trying to do so causes a compile-time error. Putting a pure
virtual function in your class signals two things to clients of your class:
- Don’t make an object of this class; derive from it.
- Be certain to override the pure virtual functions your class inherits.
Any class that derives from an abstract class inherits the pure virtual function as pure,
and so must override every pure virtual function if it wants to instantiate objects. Thus, if
Rectangleinherits from Shape, and Shapehas three pure virtual functions,Rectangle
must override all three or it, too, will be an abstract class. Listing 14.8 rewrites the Shape
class to be an abstract data type. To save space, the rest of Listing 14.7 is not reproduced
here. Replace the declaration of Shapein Listing 14.7, lines 7–16, with the declaration of
Shapein Listing 14.8 and run the program again.
LISTING14.8 Abstract Class
0: //Listing 14.8 Abstract Classes
1:
2: class Shape
3: {
4: public: