GIDForums

Go Back   GIDForums > Computer Programming Forums > CPP / C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read


 
 
Thread Tools Search this Thread Rating: Thread Rating: 2 votes, 5.00 average.
  #1  
Old 14-Apr-2005, 01:35
aaroncohn's Avatar
aaroncohn aaroncohn is offline
Regular Member
 
Join Date: Feb 2004
Location: Bay Area, CA.
Posts: 564
aaroncohn is a jewel in the roughaaroncohn is a jewel in the roughaaroncohn is a jewel in the rough

[Tutorial] Function Pointers


Function pointers

The topic of function pointers may seem advanced to those who have never tried to use them, but they get easy very quickly! In this tutorial, I will teach the reader how to declare, assign, and call pointers to functions and pointers to functions that are members of a class. For those who do not know what pointers are or how to create them, go to this tutorial to learn how to do that.

If you do know about pointers, please continue! The first thing we need to know about pointers to functions is that they are pointers. They are not actually functions, and they do not have a body. A function pointer is simply an address in the form of a function. Here is the syntax for creating a normal pointer compared to the syntax for creating a function pointer.

CPP / C++ / C Code:
// Normal pointer
float *floatptr;

// Function pointer
float (*fctnptr)();
The first thing you probably noticed about the declaration of a function pointer is the presence of parentheses around the identifier of the function pointer. This has to do with the operator precedence of the * operator. I will not talk about operator precedence here, but be aware that the parentheses must be included for the declaration to work, and that the * must be inside the parentheses.

Ok, now that we have a function pointer, we need something to point to. This is where some strict rules come into play. There is one MAJOR rule about function pointers - the signature of the function pointer must be the same as the signature of the function that it points to. It is imperative that both functions have the same return type, number of parameters, type of parameters, and order of parameters. Now I will show you how to assign the address of a function to a function pointer. Although it's optional for most compilers you should use the address operator & infront of the function's name in order to write portable code.

CPP / C++ / C Code:
// swap is the function that we will point to
int swap( int &a, int &b ) // using C++ reference variables
{
  int temp = a;
  a = b;
  b = temp;
}

// fctnptr is the function pointer that will point to swap
int (*fctnptr)( int &a, int &b );

int main()
{
  int a = 4,
      b = 7;
  fctnptr = &swap; // assign the address of swap to fctnptr (no braces!)

  cout << "a: " << a << endl;
  cout << "b: " << b << endl;
  (*fctnptr)(a,b); // call the function pointed to by fctnptr
  cout << "a: " << a << endl;
  cout << "b: " << b << endl;  
  return 0;
}
You can see that calling swap from a function pointer is much the same as accessing the data pointed to by a normal pointer.

CPP / C++ / C Code:
int main()
{
  int a = 0,
      b = 5,
     *ptr = &b;

  a = *ptr; // accessing the data pointed to by ptr
  (*fctnptr)(a,b); // accessing the function pointed to by fctnptr
  return 0;
}
At first you may ask, "Why have a pointer to a function?" Well, the answer to that question is simple. There are not many reasons to have a pointer to a function, but there are a few important ones. One such reason is the need to pass a function as a parameter to another function. This is done by functions like QuickSort (or qsort), which sorts ANY data that you give it. How does it sort any data that you give it? You write a function that compares your data and returns a value that tells whether the result was less than, greater than, or equal to. Then, you pass a pointer to that function to qsort, and qsort uses your function when comparing the values of your data as it is sorted. Very cool!

Here's another way to use function pointers. It's a simple concept, but I'll start off with a question. Have you ever had a switch statement that had a lot of branches, but all it did was decide what function to call based on the value of an integral variable (such as int or enum)? This can be simplified by creating an array of functions. Here's a quick example of what I mean.

CPP / C++ / C Code:
int func1()
{
  printf("1\n");
  return 1;
}
int func2()
{
  printf("2\n");
  return 2;
}
int func3()
{
  printf("3\n");
  return 3;
}
int main()
{
  int (*funcptr[3])();
  int x = 0;

  funcptr[0] = &func1;
  funcptr[1] = &func2;
  funcptr[2] = &func3;
  
  while ( x < 3 )
    x = (*funcptr[x])();

  return 0;
}
In addition to being able to create an array of functions, one can also create an array of functions where the functions belong to a class. The syntax is the same, but it looks a little more cryptic due to the necessity for fully qualified names (using the scope resolution operator). Here's an example of that.

CPP / C++ / C Code:
class funcs
{
  int func1()
  {
    printf("1\n");
    return 1;
  };
  int func2()
  {
    printf("2\n");
    return 2;
  };
  int func3()
  {
    printf("3\n");
    return 3;
  };
};
int main()
{
  funcs *obj = new funcs; // the class must be instantiated in order to
                          // have access to its functions, unless they 
                          // are static functions
  int (funcs::*funcptr[3])();
  int x = 0;

  funcptr[0] = &funcs::func1; // assigning the address of a member
  funcptr[1] = &funcs::func2; // function requires the use of the
  funcptr[2] = &funcs::func3; // address-of operator and :: operator
  
  while ( x < 3 )
    x = (obj->*funcptr[x])();

  delete obj;
  return 0;
}
Note that the -> operator is used because obj is a pointer to a structure, and the -> must be used to access anything that belongs to the structure. The function itself is also a pointer, hence we must use * to access the function that it points to. Such is the same with all function pointers.

This concludes my tutorial on function pointers. If you have any questions or corrections, please feel free to post them on this forum. Questions will be answered to the best of my knowledge. Corrections will be implemented as I become aware of them. Please add some rep if you liked this tutorial!
__________________
-Aaron
Last edited by aaroncohn : 14-Apr-2005 at 02:17.
  #2  
Old 23-Jul-2005, 06:12
likeit likeit is offline
New Member
 
Join Date: Jul 2005
Posts: 11
likeit is on a distinguished road
Post

i have followed the code program like this:

CPP / C++ / C Code:
#include<stdio.h>
#include<conio.h>
class funcs{

int fun1(){
printf("1\n");
return 1;
} ;

int fun2(){
printf("2\n");
return 2;
} ;

int fun3(){
printf("3\n");
return 3;
};
};

int main(){
funcs * obj=new funcs;
int (funcs::*funcptr[3]) ();
int x=0;

funcptr[0]=&funcs::fun1;
funcptr[1]=&funcs::fun2;
funcptr[2]=&funcs::fun3;

while(x<3)
 x=(obj->*funcptr[x]) ();
delete obj;
getch();
return 0;
}

i have a c++ code to compile in borland c++ ,but the error shown up like this:
funcs::fun1) is not accessible
funcs::fun2() is not accessible
funcs::fun3() is not accessible

why does the message shown up ?
how to reduce the error so the prog can run?
Last edited by admin : 15-Feb-2006 at 23:05. Reason: Please insert your C code between [c] & [/c] tags
  #3  
Old 07-Oct-2005, 02:36
aaroncohn's Avatar
aaroncohn aaroncohn is offline
Regular Member
 
Join Date: Feb 2004
Location: Bay Area, CA.
Posts: 564
aaroncohn is a jewel in the roughaaroncohn is a jewel in the roughaaroncohn is a jewel in the rough

Re: [Tutorial] Function Pointers


Of course... the default setting for members of a class is PRIVATE. You must declare them as PUBLIC in order to call them. I will correct this part of the tutorial
__________________
-Aaron
  #4  
Old 07-Feb-2006, 20:08
rwehrli
 
Posts: n/a

Re: [Tutorial] Function Pointers


Quote:
Originally Posted by aaroncohn
Of course... the default setting for members of a class is PRIVATE. You must declare them as PUBLIC in order to call them. I will correct this part of the tutorial

...or, you can employ the lazy-man's way and change "class" to "struct" and then everything is public by default! (I know, ugly--but works)


Take Care.

Rob!
  #5  
Old 17-Feb-2006, 11:33
davis
 
Posts: n/a

Re: [Tutorial] Function Pointers


Something that you may want to consider in your "next installment" of this topic is a demonstration of how to pass function pointers as arguments and to return function pointers. You may also want to show some common, real-world uses of functors...a term that I didn't notice being used in your text.


:davis:
 

Recent GIDBlogNon-US citizens serving in the military by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
[Include] Doubly-linked List dsmith C Programming Language 6 14-Apr-2006 13:12
[Tutorial] Pointers in C (Part I) Stack Overflow C Programming Language 1 08-Apr-2005 18:35
help with delete function using pointers!!! wbsquared03 CPP / C++ Forum 0 29-Nov-2004 16:32
Revising Script style ?????? pepee MySQL / PHP Forum 4 14-Apr-2004 04:59

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 18:57.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.