Concept of Callback Functions
Introduction to the concept
- Function Pointers provide the concept of Callback Functions.I hope we still remember the Generic sorting algorithm that we have talked about in the previous post .This function that sorts the items of a field according to a user-specific ranking(qsort). The field can contain items of any type, It’s passed to the sort function using void-pointer.Also the size of an element and the number of elements in the field itself has got to be passed, so if we need to write a prototype to this function will be as follows
- Lets ask !! How can this sort-function sort the elements of the field without any information about the type of an element?
- The answer is: that the Function receives the pointer to a comparison-function (int_sorter) which takes void-pointers to two field-items, evaluates their ranking and return the result as an int .So, every time the sort algorithm needs a decision about the ranking of two items, it just calls the comparison-function via Function Pointer.
- A Callback is done like a normal function call you just use the name of the function pointer instead of a function name.
How to implement a Callback to C++ Member Function?
- Static Member Functions:
- Static member functions do not need an object to be invoked.
- Non-Static Member Functions:
- In C++, classes can have Non-Static member functions have an implicit parameter (this pointer), So the type of the object must be included as part of the type function pointer.The method is then used an object of that class by using one of the “pointer-to-member” operators (“*” for an object , “->” for pointer to object)
- If you want to callback to a member specific class you just change the code from an ordinary function pointer to a pointer to a member function.
- Lets Ask !! What can I do if I want to callback to a Non-Static member of any class?
- We need to write a Static Member Function as a Wrapper function because the function does not know the type of the passed Object.
- The wrapper’s signature will be the same as the member function and pass to the function void* pointer to Object as an (Additional Argument || Global Variable ).
- The wrapper casts the void* pointer to a pointer to an instance of the correct class and call the member function.
- You can try to implement Callback to a Non-Static Member functions with Global Variable by yourself.
- Function pointer tutorials,Pointers Tutorials(C++ Documentation tutorials),C++ Professional Group(LinkedIn Answers).
Special Thanks to: Omar Enayet (C++ Developer at NTP Software).