Date post: | 20-Jan-2018 |
Category: |
Documents |
Upload: | quentin-byrd |
View: | 221 times |
Download: | 0 times |
Virtual Functions& Polymorphism
Geometric Object Example
Function also
availablein Circle & Rectagle Circle & Rectangle
could use toString() but chose to override
Dispatch
• Normal functions only use "obvious" version of function:
Virtual Functions
• virtual functionIf you are trying to use this behavior, first check for a new version in any subtypes I am
Virtual Functions
Everything else the same…
Polymorphism
• Polymorphism : many forms– Ability of one function call to produce different
results depending on exact type of object
Virtual Lookup
• On toString() call…– We know we have a
GeometricObject• Could use that toString()
GeometricObj&
GeometricObject
Circle
?
Virtual Lookup
• On toString() call…– We know we have a GeometricObject
• Could use that toString()
– But since virtual, go look for other version
GeometricObj&
GeometricObject
Circle
!!
VTables
• Vtable : Table of function pointers– Objects have pointer to vtable for their class
VTables
• Virtual Dispatch:– Start with object pointer
VTables
• Virtual Dispatch:– Look up vtable address for this object
VTables
• Virtual Dispatch:– Look up function address for desired function
VTables
• Virtual 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
Virtual Advice
• Virtual tips:– Use anytime child class may need to change
behavior of a function– Slight overhead to vtable lookup
Virtual Advice
• Virtual tips:– Declare function virtual in parent .h
– No changes to .cpp– Do not have to declare as virtual in child classes
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
Last Virtual Tip
• Classes that are inherited from should declare virtual destructor
GeometricObject* gp = //mystery pointerdelete GeometricObject;If virtual – go see if we have
child destructor to callIf NOT virtual – only useGeometricObject's destructor