Monday, October 8, 2007

What is Function Object and Its Use with Example

What is Function Object in C++ ?
Answer:- It is nothing but something like Function Pointer in "C" .Regarding Function pointer and its use , how to read , how to declare all these i have discussed in my previous article.
Points:
1)It takes the place of function pointers in traditional C programming.
2)It works by overloading operator() which in turn called as Functor in c++.
3) It is used in STL.
4) STL has more generalised ,sophisticated ,robust concept of Function pointer. i.e Function Object. So function pointer is Function object we can say.
Note -: Remember(Important) Ponter to member function in c++ (.*,->*) is not exactly function pointer in C. This is something difrent I will discuss later. It is beyond scope of this discussion.
5)So any object that can be called is a function object or FUNCTOR.
6)C function pointer is just one of the example.
7)In c++ , we can call any object ,provided it is overloaded with operator().
In Summery
1.1) A Function Object, or Functor (the two terms are synonymous)
1.2) any object that can be called as if it is a function.
1.3) To accomplish this , it must defines operator().
Example.
class Greater_Than
{
private:
int limit;
public:

Greater_Than(int a) : limit(a) { }
bool operator()(int value)

{
return value > limit;
}
};

int main()
{
Greater_Than gt_five(5);
if (gt_five(7) )

{
cout<<"7 > 5" <<>
}
else
{
cout<< "7 <= 5" <<>
}
}
Explanation
See gt_five is an object of the class Greater_Than which is constructed with value 5.
Here you just notice the statement if (gt_five(7)) , we hust calling like a function.But it is an object. So here now we understood that an object of the class can be called as if it is a function, for this we just have overload the operator ().
Now when the control encounter the statement if (gt_five(7)) then control goes to operator () which return true or false.
so we get the appropiate out put.

No comments: