- Typically, pointer-class determines functions
- virtual functions; object (not pointer) determines function called
- Why useful?
- Suppose Circle, Triangle, Rectangle
derived from Shape; each has own draw function
- To draw any shape
- Have base class Shape pointer, call draw
- Program determines proper draw function at run time (dynamically)
- Treat all shapes generically
- Declare draw as virtual in base class
- Override draw in each derived class; like redefining, but new function must have same signature
- If function declared virtual, can only be overridden
- virtual void draw() const;
- Once declared virtual, virtual in all derived
classes; good practice to explicitly declare virtual
- Dynamic binding
- Choose proper function to call at run time
- Only occurs off pointer handles; if function called from object, uses that object"s definition
- Example
- Redo Point, Circle example with virtual functions
- Base-class pointer to derived-class object; will call derived-class function
Figure 10:
Point class header file declares print function as
virtual (upper) and Circle class header file declares print function as
virtual.
|
Figure 11:
Demonstrating polymorphism by invoking a derived-class virtual
function via a base-class pointer to a derived-class object. (part 1 of 2)
|
Figure 12:
Demonstrating polymorphism by invoking a derived-class virtual
function via a base-class pointer to a derived-class object. (part 2 of 2)
|
- Polymorphism
- Same message, "print", given to many objects; all through a base pointer
- Message takes on "many forms"
- Summary
- Base-pointer to base-object, derived-pointer to derived; straightforward
- Base-pointer to derived object; can only call base-class functions
- Derived-pointer to base-object
- Compiler error
- Allowed if explicit cast made (more in section 10.9)
2004-07-26