|
|
|
|
|
|
|
× × × × ×
× × × × ×
× × × × ×
× × × × ×
(1)Circle (2)Rectangle (3)Square (0)Quit:0 |
|
|
|
|
|
|
|
|
Analysis: On lines 514, the Shape class is declared. The GetArea() and GetPerim() methods return an error value, and Draw() takes no action. After all, what does it mean to draw a shape? Only types of shapes (circles, rectangle, and so on) can be drawn; shapes as abstractions cannot be drawn. |
|
|
|
|
|
|
|
|
Circle derives from Shape and overrides the three virtual methods. Note that there is no reason to add the word virtual, as that is part of their inheritance. But there is no harm in doing so either, as shown in the Rectangle class on lines 4145. It is a good idea to include the term virtual as a reminder, a form of documentation. |
|
|
|
|
|
|
|
|
Square derives from Rectangle, 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 object, and it might be desirable to make that impossible. The Shape class exists only to provide an interface for the classes derived from it; as such, it is an abstract data type, or ADT. |
|
|
|
|
|
|
|
|
An abstract data type represents a concept (like shape) rather than an object (like circle). In C++, an ADT is always the base class to other classes, and it is not valid to make an instance of an ADT. |
|
|
|
|
|
|
|
|
C++ supports the creation of abstract data types with pure virtual functions. A virtual function is made pure by initializing it with 0, as in |
|
|
|
|
|
|
|
|
Any class with one or more pure virtual functions is an ADT, and it is illegal to instantiate an object of a class that is an ADT. Trying to do so will cause 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. |
|
|
|
|
|
|
|
|
· Make sure you override the pure virtual function. |
|
|
|
|
|
|
|
|
Any class that derives from an ADT inherits the pure virtual function as pure, and so must override every pure virtual function if it wants to instantiate objects. Therefore, if Rectangle inherits from Shape, and Shape has three pure virtual functions, Rectangle must override all three or it, too, will be an ADT. Listing 18.4 rewrites the Shape class to |
|
|
|
|
|