Sams Teach Yourself C++ in 21 Days

(singke) #1

478 Day 14


5: Shape(){}
6: ~Shape(){}
7: virtual long GetArea() = 0;
8: virtual long GetPerim()= 0;
9: virtual void Draw() = 0;
10: private:
11: };

(1)Circle (2)Rectangle (3)Square (0)Quit: 2
x x x x x x
x x x x x x
x x x x x x
x x x x x x

(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

(1)Circle (2)Rectangle (3)Square (0)Quit: 0
As you can see, the workings of the program are totally unaffected. The only dif-
ference is that it would now be impossible to make an object of class Shape.

OUTPUT


LISTING14.8 continued

ANALYSIS

Abstract Data Types
Declare a class to be an abstract class (also called an abstract data type) by including one
or more pure virtual functions in the class declaration. Declare a pure virtual function by
writing = 0after the function declaration.
Example
class Shape
{
virtual void Draw() = 0; // pure virtual
};

Implementing Pure Virtual Functions ............................................................


Typically, the pure virtual functions in an abstract base class are never implemented.
Because no objects of that type are ever created, no reason exists to provide implementa-
tions, and the abstract class works purely as the definition of an interface to objects,
which derive from it.
Free download pdf