To download of copy of the PointToFunction code written for MS Visaul C++, click
"PtrToFunc.zip"
To e-mail a suggestion or comment: sam@gilcrist.com Here is one implementation of a Pointer to a Function:
/**********************************************************************
/ Name : PtrToFunct.cpp
/ Purpose : Demonstrate how to pass a pointer to a function using OOP
/ Author : R. Sam Gilcrist
/ Date : 16 Oct 02
/*********************************************************************/
#include "stdafx.h"
#include <stdio.h>
#include "Abstract.h"
int add (int x, int y) {return x+y;}
void f (int (*PtrToFunction) (int x, int y))
{
printf ("Answer: %d.\n", PtrToFunction(67,34));
}
int main ()
{
//simplest view of ptr to function
f(add);
//Object Oriented view of ptr to function
Abstract * a = new Abstract();
//It is probably silly to pass these values to Abstract.
//The point is, though, that you cannot pass the values in using the PassFunction call,
//so the values need to be passed as they are here or they need to originate in the class
//(which is probably more realistic).
a->SetNumbers(6,7) ;
a->PassFunction(add);
printf("Press enter to quit.\n");
getchar();
return 0;
}
/**********************************************************************
/ Name : Abstract.cpp
/ Purpose : Simple class that implements 'add' passed in from PtrToFunct.cpp
/ Author : R. Sam Gilcrist
/ Date : 16 Oct 02
/*********************************************************************/
#include "stdafx.h"
#include <stdio.h>
#include "Abstract.h"
Abstract::Abstract()
{
}
Abstract::~Abstract()
{
}
//This function links the function specified in *PassedFunction via the pointer *PassedFunction
void Abstract::PassFunction(int (__cdecl *PassedFunction)(int,int))
{
int sum = PassedFunction(mFirstNumber,mSecondNumber);
printf ("The sum of %d + %d = %d.\n", mFirstNumber, mSecondNumber, sum) ;
}
/**********************************************************************
/ Name : Abstract.h
/ Note : All of the MS Visual C++ stuff is removed.
**********************************************************************/
class Abstract
{
public:
void PassFunction(int (*function) (int x, int y));
Abstract();
virtual ~Abstract();