Sunday, January 8, 2012

Using an Inheritance Hierarchy

Let's presume we've defined the five other numeric sequence classes (Pell, Lucas, Square,
Triangular, and Pentagonal) in the same manner as the Fibonacci class. We now have a two-level
inheritance hierarchy: an abstract num_sequence base class and the six inheriting derived classes.
How might we use them?
Here is a simple display() function whose second parameter is ns, a const reference to a
num_sequence object.


Within display(), we call the two virtual functions what_am_i() and elem() . Which
instances of these functions are invoked? We cannot say for certain. We know that ns does not
refer to an actual num_sequence class object but rather to an object of a class derived from
num_sequence. The two virtual function calls are resolved at run-time based on the type of theclass object ns refers to. For example, in the following small program I define an object of each
derived class in turn and pass it to display():


Running Codes
inline void display(ostream &os,
const num_sequence &ns, int pos)
{
os << "The element at position "
<< pos << " for the "
<< ns.what_am_i() << " sequence is "
<< ns.elem(pos) << endl;
}


int main()
{
const int pos = 8;
Fibonacci fib;
display(cout, fib, pos);
Pell pell;
display(cout, pell, pos);
Lucas lucas;
display(cout, lucas, pos);
Triangular trian;
display(cout, trian, pos);
Square square;
display(cout, square, pos);
Pentagonal penta;
display(cout, penta, pos);
}

No comments:

Post a Comment