Now that num_sequence declares actual data members, we must provide for their initialization.
We could leave it to each derived class to initialize these data members, but that's potentiallyerror-prone. A better design is to provide a base class constructor to handle the initialization of all
base class members.
Recall that num_sequence is an abstract base class. We cannot define an independent object of its
class; rather, the num_sequence serves as a subobject of each derived cla ss object. For this reason,
we declare the base class constructor to be a protected rather than public member.
The initialization of a derived class object consists of the invocation of the base class constructor
followed by that of the derived class constructor. It helps to think of the derived class object as
consisting of multiple subobjects: a base class s ubobject initialized by the base class constructor
and a derived class subobject initialized by the derived class constructor. In a three-level class
hierarchy, such as the AudioBook class of Section 5.1, the derived class consists of three
subobjects, each one initialized by its respective constructor.
The design requirements of a derived class constructor are twofold: Not only must it initialize the
derived class data members, but it must also supply the expected values to its base class
constructor. In our example, the num_sequence base class requires three values that are passed to
it using the member initialization list. For example,
If we should overlook the invocation of the num_sequence constructor, the definition of the
Fibonacci constructor is flagged as an error. Why? The num_sequence base class requires our
explicit invocation of its three-argument constructor. In our design, this is what we want.
Alternatively, we could provide a default num_sequence constructor. We must change _relems
to a pointer, however, and add code to verify th at it is non-null before each access of the vector:
Running Codes
inline Fibonacci::
Fibonacci(int len, int beg_pos)
: num_sequence(len, beg_pos, &_elems)
{}
num_sequence::
num_sequence(int len=1, int bp=1, vector *pe=0)
: _length(len), _beg_pos(bp), _pelems(re){}
No comments:
Post a Comment