|
|
|
|
|
|
|
class's default constructor. When an ExtTime object is created with the declaration |
|
|
|
|
|
|
|
|
the ExtTime class's default constructor first implicitly calls Time's default constructor, after which its body executes, setting zone to EST. |
|
|
|
|
|
|
|
|
Next, look at the Set function in Figure 16-6. This function overrides the Set function inherited from the base class. Consequently, there are two distinct Set functions, one a public member of the Time class, the other a public member of the ExtTime class. Their full names are Time::Set and ExtTime::Set. In Figure 16-6, the ExtTime::Set function begins by reaching up into its base class and calling Time::Set to set the hours, minutes, and seconds. (Remember that a class derived from Time cannot access the private data hrs, mins, and secs directly; these variables are private to the Time class.) The function then finishes by assigning a value to ExtTime's private data, the zone variable. |
|
|
|
|
|
|
|
|
The Write function in Figure 16-6 uses a similar strategy. It reaches up into its base class and invokes Time::Write to output the hours, minutes, and seconds. Then it outputs a string corresponding to the time zone. (Recall that a value of enumeration type cannot be output directly in C++. If we were to print the value of zone directly, the output would be an integer from 0 through 7the internal representations of the ZoneType values. The Write function establishes an array of eight strings and selects the correct string by using zone to index into the array.) |
|
|
|
|
|
|
|
|
Now we can compile the file exttime.cpp into an object code file, say, exttime.obj. After writing a test driver and compiling it into test.obj, we can obtain an executable file by linking three object files: |
|
|
|
|
|
|
|
|
1. test.obj
2. exttime.obj
3. time.obj |
|
|
|
|
|
|
|
|
We can then test the resulting program. |
|
|
|
|
|
|
|
|
The remarkable thing about derived classes and inheritance is that modification of the base class is unnecessary. The source code for the implementation of the Time class may be unavailable. Yet variations of this ADT can continue to be created without that source code, in ways the creator never even considered. Through classes and inheritance, OOP languages facilitate code reuse. A class such as Time can be used as-is in many different contexts, or it can be adapted to a particular context by using inheritance. Inheritance allows us to create extensible data abstractionsa derived class typically extends the base class by including additional private data or public operations or both. |
|
|
|
|
|