Friday, 6 March 2009

Simple example of Callback Functions

Here is a simple example introducing to the concept of callbacks in C++. Function Pointers will be used implicitly in demonstrating this example.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example showing how callback functions work in C++
#include<iostream>

using namespace
std;

int
adds(int a, int b)
{

return
a+b;
}


int
subs(int a, int b)
{

return
a-b;
}


int
DoIt(int x, int y, int (*c)(int, int))
{

cout<<"DoIt : "<<c(x,y)<<endl;
return
0;
}


int
main()
{

DoIt(3,4,adds);
DoIt(4,3,subs);

//subs by another name
int (*minus)(int,int) = subs;
DoIt(4,2,minus);

return
0;
}


2 comments:

  1. sample output for this?

    ReplyDelete
  2. It should be something like:

    DoIt : 7
    DoIt : 1
    DoIt : 2

    ReplyDelete