|
|
|
|
|
|
|
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, there is no reason to provide implementations, and the ADT works purely as the definition of an interface to objects that derive from it. |
|
|
|
|
|
|
|
|
It is possible, however, to provide an implementation to a pure virtual function. The function can then be called by objects derived from the ADT, perhaps to provide common functionality to all the overridden functions. Listing 18.5 reproduces Listing 18.3, this time with Shape as an ADT and with an implementation for the pure virtual function Draw(). The Circle class 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 you can imagine that the base class provides a shared drawing mechanism, perhaps setting up a window that all derived classes will use. |
|
|
|
|
|
|
|
|
LISTING 18.5 IMPLEMENTING PURE VIRTUAL FUNCTIONS |
|
|
|
 |
|
|
|
|
1: //Implementing pure virtual functions
2:
3: #include <iostream.h>
4:
5: class Shape
6: {
7: public:
8: Shape(){}
9: virtual ~Shape(){}
10: virtual long GetArea() = 0; // error
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: ~Circle(){} |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|