UMBC CMSC202, Computer Science II, Spring, 1999 Sections 0201 and 0202

Virtual Functions and Dynamic Binding

[Next Lecture] [Previous Lecture]
Files used in this week's lectures

Generic classes

The problem we addressed ths week is makng our classes generic, i.e. to allow them to work with many different types of data. The name you often hear in this regard is "polymorphism". Virtual functions enable us to accomplish this desirable result.

A virtual function is found in the GenArray class. We declare the function print as

  virtual void print() = 0;

This has the effect of saying to the compiler: the implementation of print will not be given ffor the GenArray class (which makes sense - note that there aren't any array members in the class). When there is pure virtual function in a class, then we may not declare any objects of that class. In particular, we may not create any object of type GenArray. The only thing we can do with GenArray is use it as a base class.

when we implement GenArray, we provide a generic sort program (bubble sort), and we use the functions cmp and swapto do the comparison and exchange of elements. Note that both of these functions are declared as virtual, and that they use array indices (not array elements)as arguments. This allows us to avoid any type information in the class declaration and int eh sort definition.

The derived classes IntArray and FloatArray have an array as an appendant member; They also include implementations of the virtual functions in teh base class.

The second example, general lists, is more interesting. We use the ListCell class for deriving integer (IntCell) and string (StringCell) classes. Once we do this, we can have lists which contain a mixture of int cells and string cells.

Some technical issues:

  1. List cell's destructor is virtual. This is necessary because, when list's destructor is invoked, it must invoke the correct destructor for the cell (an IntCell or StringCell).
  2. Note that the virtual function clone() in ListCell is used in a number of places to make copies of cells. clone returns a listcell pointer, but it could point to any derived object.
  3. We did a little trick to assure that when we compare cells, we are comparing cells of the same type. The virtual id() function returns the address of the static member idvar. Each class has its own static member idvar. As idvar is static, each class instance will have the same id(). This guarantees that when we compare intcells (for example) to non-intcells, we are guaranteed a not-equal comparison, and for items to compare as equal, they must both be of the same type.


    Last Modified: 25 Apr 1999 23:05:57 EDT by Mitch Edelman edelman@cs.umbc.edu

    Back up to Spring 1999 CMSC 202 Section Homepage