Tutorial - C / C++ - Function Pointers


Coding Friends Tutorial Index - > C / C++

Author Ian - Tutorial Posts = 62
Function pointers are just like any other type of pointer within C/C++, in that they point to a reference in memory to something that is the “hard” reference to the object (a pointer to a integer type that is holding the value 2 is the “hard” value of 2 and the pointer just points to this object). Since a pointer can point to any type of object that is similar to the object type, you can also have pointers to functions. This type of pointer is good for having a single function pointer to list of functions that is chosen from a action, for example if there was a list of function for the edit action within the standard document editors (Cut/Copy/Paste/Undo/Redo) and to just point to within every function was required was to use the drop down list item number, then the code is very small and also re-usable.

For example of code with using function pointers.
---


#include <iostream>

using namespace std;

void f()
{
       cout << "hi" << endl;       
}

void g()
{
       cout << "bye" << endl;
}

// always set the function pointer to NULL.
void (*func)() = NULL;

// to pass a function pointer to a function.
void callFunc( void (*function)())
{
       function();
}

int main(int argc, char* argv[])
{
       // set the func object (as created above – void (*func)() = NULL; - to the function address f)
       func=&f;
       // call the function that is assoicated with the func pointer
       func();
       // reset to another function.
       func=&g;
       func();

       // call the function pointed to within another function.
       callFunc(func);
       return 0;
}


---
I have included Microsoft Visual Studio 2005 downloadable edition (here) and also Linux code for this tutorial as a download.
Creation of cool tutorials :)
User Name Password
Copyright@CodingFriends, 2005-2006. All Rights Reserved.
Home | Forums | Tutorials | Users
RSS Feeds - Global Global CodingFriends RSS Feed - Tutorials Tutorials CodingFriends RSS Feed - Forums Forums CodingFriends RSS Feed - News News CodingFriends RSS Feed
Users
Login|Password problem| Register here

Tutorials
Tutorials Home| C/C++| C#/Mono| Java| Javascript| PHP| Ruby| SQL| (X)HTML/CSS| VB| Linux| Windows

Forum
Forum Home

Projects
3D Game

Site
Home| About me| Links| FAQ

Search