Wednesday, 28 January 2015

Function pointers with overloaded function in C++ with example

Function pointers with overloaded function in C++ with example:

The use for function pointers is setting up "listener" or "callback" functions that are invoked when a particular event happens. The function is called, and this notifies your code that something of interest has taken place.

The overloaded functions are perform in the following seven contexts.

1) The initializer in a declaration of an object or reference
2) It is on the right-hand-side of an assignment expression
3) It is like a function call argument
4) as a user-defined operator argument
5) the return statement
6) explicit cast or static cast argument
7) non-type template argument

In each context, the name of an overloaded function may be preceded by address-of operator & and may be enclosed in a redundant set of parentheses.
Function Pointers Syntax:

Declaring the function pointers:

Declare a function pointer as though you were declaring a function, except with a name like *myFunc instead of just myFunc:
void (*myFunc)(double); 

Initializing the function pointers:

void myFunc();

func_pointer = myFunc; 

or by prefixing the name of the function with an ampersand:
void myFunc();

func_pointer = &myFunc;

Invoking the function pointers:

Invoke the function pointed to just as if you were calling a function.
func_pointer( arg1, arg2 ); 

or you may optionally dereference the function pointer before calling the function it points to:
(*func_pointer)( arg1, arg2 ); 

 Let us see the sample program that contains the overloaded functions.
using namespace std;

 #include <iostream>

void ExFunction(int iCount)

{

  for( ; iCount; iCount--)

     cout << ' ';

}

void ExFunction(int iCount, char chVal)

{

  for( ; iCount; iCount--)

     cout << chVal;

}

int main (int nNumberofArgs, char* pszArgs[])

{

   void (*FP1)(int);

  void (*pcFunPtr)(int, char);

  FP1 = ExFunction;                 

  pcFunPtr = ExFunction;               

  FP1(12);                     

  cout << "|\n";

  pcFunPtr(130, 'x');               

  cout << "|\n";

  return 0;

}

The output of the above program is:
       |

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx|


No comments: