Callbacks C++

If you like this post, please visit our sponsors above. Thanks!

This tutorial assumes that the reader has a basic knowledge of C++ function pointers and pointers to class member functions.

Callback function

A callback function is a function whose pointer is passed to another function and and that function calls the first function using the pointer. When such a call is made, it is said that a callback has been made.

Why use a Callback?

You must be wondering why use a callback? Consider the scenario where you are implementing a sorting technique based on comparisons. You want it to be generic and allow the user to choose which number goes first (ascending sort or descending sort). To solve this you can have the user pass a function to your sort program and you can use that function to decide which number goes first. Here you are only making a callback and you do not care how or where the function is implemented, neither does the writer of the passed function care who or where the caller is.

How its done?

First i create a class for sorting numbers that requires a callback function and makes a callback.

   1: class SortNumber

   2: {

   3: public: 

   4:     SortNumber(int * a, int s)

   5:     {

   6:         arr = a;

   7:         size = s;

   8:     }

   9:  

  10:     void Sort( bool (*sortOrder(int , int)) )

  11:     {

  12:         // sort algorithm that uses the sortOrder

  13:         // as (*sortOrder)(firstNum, secondNum);

  14:     }    

  15: };

In the above code we have a class that sort an array of integers. In all comparison sorts, we need to be able to make decision whether two number are out of place or not. However, this decision can be made in a variety of ways (Can you figure out why a variety of ways and not just two?). The user can then supply a function of their own choosing how different numbers are treated in comparison.

The comments inside the sort function also show how to make the call back. This whole exercise when a function pointer is passed to another function and the pointer is used to call that function is called a callback.

If you like this post, please visit our sponsors blow. Thanks!

One Response to “Callbacks C++”

  1. zabardast, thnx bro this solved my problem :D

Leave a Reply