Thursday, June 07, 2012

Function Pointer and Overloading Function Call

http://en.wikipedia.org/wiki/Function_pointer
Function pointers are a complex and powerful in C/C++. It runs faster the tradition function because it only passes the pointer. They allow to pass one function as an argument to another function.
#include <iostream>
using namespace std;
int myfunc(int a);
int myfunc(int a, int b);
int main()
{
    int (*fp)(int a, int b);
    fp = myfunc; // points to myfunc(int)
    cout << fp(5, 2 );
    return 0;
}
int myfunc(int a)
    {
    return a;
    }
int myfunc(int a, int b)
    {
    return a*b;
    }
Using a function pointer
Once you define a pointer to a function, you must assign it to a
function address before you can use it. Just as the address of an
array arr[10] is produced by the array name without the brackets
(arr), the address of a function func() is produced by the function
name without the argument list (func). You can also use the more
explicit syntax &func(). To call the function, you dereference the
pointer in the same way that you declared it (remember that C and
C++ always try to make definitions look the same as the way they
are used). The following example shows how a pointer to a
function is defined and used:
#include <iostream>

using namespace std;
void func() {
cout << "func() called..." << endl;
}
int main() {
    void (*fp)(); // Define a function pointer
    fp = func; // Initialize it
    (*fp)(); // Dereferencing calls the function
    void (*fp2)() = func; // Define and initialize
    (*fp2)();
}
Overloading Function Call operator(). The function call operator when overloaded, does not modify how functions are called, it modifies how the operator is to be interpreted when applied to objects of a given type.
struct A {
  void operator()(int a, char b, ...) { }
//called eclipsis a variable numbers following
  void operator()(char c, int d = 20) { }
};

int main() {
  A a;
  a(5, 'z', 'a', 0);
  a('z');
//  a();
}
///////////////
class Point {
private:
  int x, y;
public:
  Point() : x(0), y(0) { }
  Point& operator()(int dx, int dy) {
    x += dx;
    y += dy;
    return *this;
  }
};

int main() {
  Point pt;

  // Offset this coordinate x with 3 points
  // and coordinate y with 2 points.
  pt(3, 2);

//////In case of Functor
#include <iostream>
using namespace std;
class myFunctorClass
{
    public:
//        myFunctorClass (int x) : _x( x ) {cout << x << endl;}
     myFunctorClass (int x) {_x =x ; cout << x << endl;}
        int operator() (int y,...) { return _x + y; }  //Overloading Function Calls(function call operator)
    private:
        int _x;
};

int main()
{
    myFunctorClass addFive( 5 );  //constructor create _x = 5
    std::cout << addFive( 6 ) << endl;
     std::cout << addFive( 6 );

    return 0;
}


      Ref: IBM
      Cprogramming

No comments: