function objects

Is there a difference between function objects, functors and function pointers or are they same?
Last edited on
functors and function objects are the same
eg:
1
2
3
4
5
6
7
8
class C
{
    double operator() ( double x ); // operator () overloaded
};

C functor;

functor(123); // you can use functor as a function thanks to the () operator 


function pointers are a different thing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
double function1 ( double x, double y )
{
   return x+y;
}


double function2 ( double x, double y )
{
   return x-y;
}

double (*function_pointer) ( double, double ); // declaring function_pointer

function_pointer = function1; //assign function_pointer to function1
function_pointer ( 5, 3 ); // returns 8, the same as function1

function_pointer = function2; //assign function_pointer to function2
function_pointer ( 5, 3 ); // returns 2, the same as function2
Thanks Bazzy.

Here's the code I've written:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
struct greaterThan: public binary_function<int, int, bool>
{
	bool operator()(const int &i1, const int &i2) const
	{
		return (i1 > i2);
	}
};

void populateSet(set<int, greaterThan> &si)
{
	si.insert(10);
	si.insert(11);
	si.insert(12);
}

void displaySet(const int &integer)
{
	cout << integer << endl;
}
	
int main()
{
	set<int, greaterThan> si;
	populateSet(si);
	for_each(si.begin(), si.end(), displaySet);
}


By default a set sorts its elements in ascending order. The above code compiled and displays numbers in descending order, which is fine. I thought that the code would not compile due to the last parameter in for_each loop. I thought that the last parameter should be passing a parameter to the calling function. Is that correct?
No, all for_each() does is apply a function to a sequence container.

Hope this helps.
Thanks Duoas and Bazzy once again. I appreciate your help.
Topic archived. No new replies allowed.