Download presentation
Presentation is loading. Please wait.
Published byQuentin Byrd Modified over 9 years ago
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() GeometricObj& Geometric Object Circle ?
8
Virtual Lookup On toString() call… – We know we have a GeometricObject Could use that toString() – But since virtual, go look for other version GeometricObj& Geometric Object Circle !!
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: – 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
17
Last Virtual Tip Classes that are inherited from should declare virtual destructor GeometricObject* gp = //mystery pointer delete GeometricObject; If virtual – go see if we have child destructor to call If NOT virtual – only use GeometricObject's destructor
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.