i recently read that we can pass function to a function by using pointer to a function.
i tried with an simple example.i defined sum function and passed it to average function so that it calculated average of return value from sum and 2 more nos..
rather than convenience point of view i found it complicated...is there any application of this concept?:?:

Recommended Answers

All 3 Replies

Look at the STL algorithm header, there is a whole load of functions using this concept, like std::count_if() .

Also, if you want to compute an integral over a range, I found it preferable to pass the integrated function as a pointer, but that's a whole another case and may not be true in general.

try this

int add(int num1,int num2)
	{
		return num1+num2;
	}
	int sub(int num1,int num2)
	{
		return num1-num2;
	}
	void test(int (*ptr2Func)(int, int))
	{
		int res=ptr2Func(1,2);
	}
	void callTest()
	{
		test(&add);
	}

Actually, mazzica1 is not quite correct. Just use the name of the function. You don't need the address operator. IE,

void callTest()
{
    test(add);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.