9. Function pointers & Virtual/non-virtual functions
02/03/23
Function Pointers
- Stored in memory
- Can ask for the address of them
- Can store these in function pointers
- Used a lot in low-level programming
- Function pointers can be passed into functions
- Used for 'callback functions'
- Allows something to call you back
- 'Call this function when an event happens'
- Event driven programming is VERY common
v-tables
Normal/default (non-virtual
) functions
- Type of pointer determines function to call
- Use the type of the object the compiler thinks it is:
- Type of pointer to the object
- Type of the member function making the call
- Easier for the compiler, type is known at compile-time
Virtual Function
- Finds out the actual function to call based upon the object type AT RUNTIME - much more difficult - slower
- Works in the same way as Java functions
Special Cases
virtual
-ness is inherited- If a function is
virtual
in the base class then the function isvirtual
in the derived class(es) - Even when the keyword
virtual
is not used in the derived class
Should a function be virtual
?
- If member function is called from a base class function or through a base class pointer AND the behaviour should depend on class type of the object then the member function has to be
virtual
- Utility functions will often not be
virtual