pointers to functions

Hi,

I've been looking into pointers to functions and have made an example program which implements a pointer to a function passed into another function as a parameter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int addition(int a, int b){ return a+b; }
int subtraction(int a, int b){ return a-b; }
int multiplication(int a, int b){ return a*b; }
int division(int a, int b){ return a/b; }

int doSum(int a, int b, int (*func)(int,int))
{
    return (*func)(a,b);
}

int main()
{
	int (*op)(int,int) = multiplication;
    
	cout << doSum(7, 5, op) << endl;
	cout << doSum(10,5,op) << endl;
	cout << doSum(17,19,addition) << endl;

	system("PAUSE");
	return 0;
}


I have two questions, firstly, can anyone give me examples of when passing a pointer to a function as an argument would be required.

Secondly, I am slightly confused about the syntax, the asterisk character is used for several different things in c++ and I can't get my head around this particular use. Why must we wrap the name of the pointer to the function in parenthesis, and how does the compiler understand (*op), when there is no data type preceding the asterisk.

Thanks.
int *op(int,int) declares a function returning a pointer to int and taking two int parameters
int (*op) (int,int) says that op is a pointer to function
Last edited on
An exemple could be to simulate class inheritance in C.
The abstract base class would be a struct with method pointers, and each child class would be an instance of this struct with it's function pointers initialized to the child's specific code.

Why the () around (*op)? Just to distinguish the * for the function pointer and for the return type i guess. The compiler wouldn't be able to tell if
char**func()
is a function returning a char** or a function pointer to a function returning a char*
An example is qsort().

The algorithm is the same, irrespective of what you want to sort, but it needs to know how to compare elements, so the compare function is passed in as a parameter.

http://en.wikipedia.org/wiki/Qsort
ok that makes sense. In the DoSum() function then:

return (*func)(a,b);

is the asterisk dereferencing the pointer, func, just like any other pointer? And if so why are the parenthesis needed here, why is return *func(a,b); not valid?
for your func, the compiler would understand return *func(a,b) as "calculate func(a,b), and dereference the rerturned pointer". S i guess you would have a first error telling that func is not a function but avariable, or an error telling that func doesn't return a pointer
Topic archived. No new replies allowed.