CS 250 Computer Programming and Problem Solving - FALL 1998 

[ Home | Syllabus | Notes | Glossary | CS250 WEB Version Home Page | Project Page | Final Study Guide]


Polymorphism

Static binding: variable is bound to a type at compile time.

Dynamic binding: variable is bound to a type at run time

C++ supports dynamic binding of objects related by inheritance (through vtables).

 


class Employee {
public:
   void CalcPay();
//...
};
class SalariedEmployee: public Employee {
public:
   void CalcPay();
//
};

 


Notice that SalariedEmployee has overriden the function CalcPay. Now consider


Employee chris;
SalariedEmployee pam;
pam.CalcPay();	// will call SalariedEmployee's CalcPay
chris.CalcPay(); // will call Employee's CalcPay (different objects, differnt member functions
}

What is you want to be able to call the correct CalcPay from any kind of Employee stored in a list.

First could not have a list containing both kinds of employees. WHY? because they probably take up a different amount of space - so the compiler won't be able to decide. - but We could use pointers in the list (which are the same size regardless of which object they are pointing at.

 


SeqList<Employee *> myList;
Employee * worker;
myList.Reset();
while(myList.Advance()) {
   worker = myList.Get();
   worker->CalcPay();
}

 


"myList" can store pointers to Employee and SalariedEmployee. How does compiler know which CalcPay to use? It checks the type at run time and then calls the proper function after looking it up in the vtable.

However, to make sure the compiler generates a vtable - you have to declare the function as a "virtual" function.

Can you guess what the "v" in "vtable" stands for?


 

class Employee {
public:
   virtual void CalcPay();
//...
};
class SalariedEmployee: public Employee {
public:
   virtual void CalcPay();
//
};

 


The ability of an object to represent more than one class is called polymorphism. This overloading of a variable, means that functions which use these variables can work for any of the family of inhertied classes.

 


Pure Classes

Sometimes a base class is used purely as a building block for derived classes and is never used by itself.

Such classes are called abstract classes. To be an abstract class, at least one function msut be a pure virtual function.

A pure virtual function is denoted by the pure-specifier "=0" following the funciton signature in the class definition.

For Example



Copyright chris wild 1998.
For problems or questions regarding this website contact [Chris Wild (e-mail:wild@cs.odu.edu].
Last updated: December 06, 1998.

 

class Employee { // abstract class (because of pur virtual
public:
   virtual void CalcPay() = 0; // pure virtual function
//...
};
class SalariedEmployee: public Employee {
public:
   virtual void CalcPay();
//
};