C++ – a callback? What is it for and how is it implemented in for example C++


I realise this is a newbie question, but as I'm trying to learn C++ I'm stumpling upon this expression "callback" frequently. I've googled it and checked wikipedia, but without finding a good explination. I am familiar with some Java and C#, but how unlikely it sounds, I have never really understood what a callback means.

If someone know how to explain this term to a simple layman, I would be really thankfull.

Best Solution

I am familiar with some Java and C#

A callback is an event or delegate in those languages - a way to get your code run by somebody else's code in it's context. Hence, the term "callback":

  1. You call some other piece of code
  2. It runs, perhaps calculating an intermediate value
  3. It calls back into your code, perhaps giving you that intermediate value
  4. It continues running, eventually passing control back to you by completing

A canonical example is a sort routine with a user defined comparison function (the callback). Given a sort routine such as:

void Sort(void* values, int length, int valueSize, 
          int (*compare)(const void*, const void*) 
   for (int i = 0; i < length; i = i + 2) {
      // call the callback to determine order
      int isHigher = compare(values[i], values[i + 1]);
      /* Sort */

(The specifics of how the sort is performed isn't important - just focus on the fact that any sorting algorithm needs to compare 2 values and determine which is higher.)

So, now we can define some comparison functions:

int CompareInts(const void* o, const void* p) {
   int* a = (int*) o;
   int* b = (int*) p;

   if (a == b) return 0;
   return (a < b) ? -1 : 1;

int ComparePersons(const void* o, const void* p) {
   Person* a = (Person*) o;
   Person* b = (Person*) p;

   if (a == b) return 0;
   return (a->Value() < b=>Value()) ? -1 : 1;

And reuse the same sort function with them:

int intValues[10];
Person personValues[10];

Sort(intValues, 10, sizeof(intVaues[0]), CompareInts);
Sort(personValues, 10, sizeof(personVaues[0]), ComparePersons);

Things get a bit more complicated if you're using member functions, as you have to manage the this pointer - but the concept is the same. As with most things, it's easier to explain them in C first. ;)