Sams Teach Yourself C++ in 21 Days

(singke) #1
Polymorphism 479

14


It is possible, however, to provide an implementation to a pure virtual function. The
function can then be called by objects derived from the abstract class, perhaps to provide
common functionality to all the overridden functions. Listing 14.9 reproduces Listing
14.7, this time with Shapeas an abstract class and with an implementation for the pure
virtual function Draw(). The Circleclass overrides Draw(), as it must, but it then chains
up to the base class function for additional functionality.
In this example, the additional functionality is simply an additional message printed, but
one can imagine that the base class provides a shared drawing mechanism, perhaps set-
ting up a window that all derived classes will use.

LISTING14.9 Implementing Pure Virtual Functions


0: //Listing 14.9 Implementing pure virtual functions
1:
2: #include <iostream>
3: using namespace std;
4:
5: class Shape
6: {
7: public:
8: Shape(){}
9: virtual ~Shape(){}
10: virtual long GetArea() = 0;
11: virtual long GetPerim()= 0;
12: virtual void Draw() = 0;
13: private:
14: };
15:
16: void Shape::Draw()
17: {
18: cout << “Abstract drawing mechanism!\n”;
19: }
20:
21: class Circle : public Shape
22: {
23: public:
24: Circle(int radius):itsRadius(radius){}
25: virtual ~Circle(){}
26: long GetArea() { return 3.14 * itsRadius * itsRadius; }
27: long GetPerim() { return 2 * 3.14 * itsRadius; }
28: void Draw();
29: private:
30: int itsRadius;
31: int itsCircumference;
32: };
33:
34: void Circle::Draw()
Free download pdf