Presentation is loading. Please wait.

Presentation is loading. Please wait.

Virtual Functions & Polymorphism

Similar presentations


Presentation on theme: "Virtual Functions & Polymorphism"— Presentation transcript:

1 Virtual Functions & Polymorphism

2 Geometric Object Example
Function also available in Circle & Rectagle Circle & Rectangle could use toString() but chose to override

3 Dispatch Normal functions only use "obvious" version of function:

4 Virtual Functions virtual function If you are trying to use this behavior, first check for a new version in any subtypes I am

5 Virtual Functions Everything else the same…

6 Polymorphism Polymorphism : many forms
Ability of one function call to produce different results depending on exact type of object

7 Virtual Lookup ? On toString() call… We know we have a GeometricObject
Could use that toString() Geometric Object Circle ? GeometricObj&

8 Virtual Lookup !! On toString() call…
We know we have a GeometricObject Could use that toString() But since virtual, go look for other version Geometric Object Circle !! GeometricObj&

9 VTables Vtable : Table of function pointers
Objects have pointer to vtable for their class

10 VTables Virtual Dispatch: Start with object pointer

11 VTables Virtual Dispatch: Look up vtable address for this object

12 VTables Virtual Dispatch:
Look up function address for desired function

13 VTables Virtual Dispatch: Normal Dispatch: Start with object pointer
Look up vtable address for this object Look up function address for desired function Call that function Normal Dispatch: Call the function

14 Virtual Advice Virtual tips:
Use anytime child class may need to change behavior of a function Slight overhead to vtable lookup

15 Virtual Advice Virtual tips: Declare function virtual in parent .h
No changes to .cpp Do not have to declare as virtual in child classes

16 Other modifiers C++11 adds override and final
Final : Child classes cannot provide new versions Override : Make sure I am actually overriding a parent function


Download ppt "Virtual Functions & Polymorphism"

Similar presentations


Ads by Google