pointer to a function c++ code example

Example 1: Function pointer C++

void one() { cout << "One\n"; }
void two() { cout << "Two\n"; }


int main()
{
	void (*fptr)(); //Declare a function pointer to voids with no params

	fptr = &one; //fptr -> one
	*fptr(); //=> one()

	fptr = &two; //fptr -> two
	*fptr(); //=> two()

	return 0;
}

Example 2: c function pointer

//Declaration of a pointer to a function that takes an integer 
//and returns an integer.
int (*f_ptr)(int);

//Assignment of a function foo to the function pointer f_ptr declared above.
f_ptr = foo;

//Calling foo indirectly via f_ptr, passing the return value of foo to r.
int r = f_ptr(v);

//Assigning an address of a function to the function pointer f_ptr,
//then calling foo by dereferencing the function pointer.  
f_ptr = &foo;
int r = (*f_ptr)(v);

Example 3: pointers to pointers in cpp

#include <iostream>
 
using namespace std;
 
int main () {
   int  var;
   int  *ptr;
   int  **pptr;

   var = 3000;

   // take the address of var
   ptr = &var;

   // take the address of ptr using address of operator &
   pptr = &ptr;

   // take the value using pptr
   cout << "Value of var :" << var << endl;
   cout << "Value available at *ptr :" << *ptr << endl;
   cout << "Value available at **pptr :" << **pptr << endl;

   return 0;
}

Tags:

Cpp Example