Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 86,251 C++ Programmers. There are 2,149 online right now! Ask your question and get quick answers from Dream.In.Code experts. Join the #1 programming help community on the internet! Registration is fast and FREE... Join Now!

Chat LIVE With a C++ Expert
Powered by LivePerson.com

Register to Make This Box Go Away!

Basics Of Function Pointers

 
Reply to this topicStart new topic

> Basics Of Function Pointers, What are function pointers and how to use them

Rating  4
AmitTheInfinity
Group Icon



post 9 Feb, 2007 - 03:57 AM
Post #1


This is my first tutorial. Though I tried my best, please forgive me for spelling and grammer mistakes.
And don't forget to comment and rate me so I will perform better next time. biggrin.gif

If you can't get it properly from post then you can download the document attached.


Function Pointers

Introduction
Function Pointers provide some extremely interesting, efficient and elegant programming
techniques. We can use them to replace switch/if statements, to realize our own late-binding or to
implement callbacks. Unfortunately probably due to their complicated syntax they are treated quite step
motherly in most computer books and documentations. If at all, they are addressed quite briefly. They
are less error prone than normal pointers cause we will never allocate or de-allocate memory with them.
All we’ve got to do is to understand what they are and to learn their syntax. But keep in mind:
It’s important to check whether we really need a function pointer. It’s nice to realize one’s own late-binding
but to use the existing structures of C++ may make our code more readable and clear.

What Is a Function Pointer ?
Function Pointers are pointers, i.e. variables, which point to the address of a function. We must
keep in mind, that a running program gets a certain space in the main-memory. Both, the executable
compiled program code and the used variables, are put inside this memory. Thus a function in the program
code is, like e.g. a character field, nothing else than an address. It is only important how we, or better our
compiler/processor, interpret the memory a pointer points to.

How To Define a Function Pointer ?
Since a function pointer is nothing else than a variable, it must be defined as usual.
Let’s take an example, we will define function pointers ptrToFunc, ptrToMember and
ptrToConstMember. The first is for C and will point to function which takes float and char as parameters and
returns integer.
Other Two are for C++ and will point to functions which takes float and char as parameters
and returns integer and are non-static members of class MyClass.
CODE

int (*ptrToFunc)(float, char) = NULL; // in C
int (MyClass::*ptrToMember)(float, char) = NULL; // C++
int (MyClass::*ptrToConstMember)(float, char) const = NULL; // C++

So in general we can say it is something like :

<return datatype of function> (* <pointer name>) (<parameters of function>);

[ It is a good practice to initialize function pointers with NULL. ]

How To Assign An Address to A Function Pointer ?
It’s quite easy to assign the address of a function to a function pointer. Simply take the name of a
suitable and known function or member function. Although it’s optional for most compilers we should use the
address operator “&” in front of the function’s name in order to write portable code. We may have got to use
the complete name of the member function including class-name and scope-operator "::" [For C++]. Also we
have got to ensure, that we are allowed to access the function right in scope where our assignment stands.
CODE

// C
int SendIt (float a, char b)
{ printf("SendIt %f\n",a); return atoi(b); }

int SendIt2(float a, char b) const
{ printf("SendIt2 %f\n",a); return atoi(b); }

ptrToFunc = SendIt; // short form
ptrToFunc = &SendIt; // correct assignment using address operator


// C++
class MyClass
{
public:
int SendIt (float a, char b)
{ cout << "MyClass::SendIt "<<a<<endl; return atoi(b); }

int SendIt2(float a, char b)const
{ cout << "MyClass::SendIt2”<<a<<endl; return atoi(b); }

/* more code will follow*/
};

ptrToConstMember = &MyClass::SendIt2; // correct assignment using address
//operator
ptrToMember = &MyClass::SendIt;
// ptrToMember can also legally point to &MyClass::SendIt2


How To Call a Function using a Function Pointer ?
In C we call a function using a function pointer by explicitly dereferencing it using the * operator.
Alternatively we may also just use the function pointers instead of the function name. In C++ the two operators “.*”
and “->*” are used together with an instance of a class in order to call one of their (non-static) member functions. If
the call takes place within another member function we may use the “this” pointer.
CODE

int result1 = ptrToFunc(12, ’a’); // C short way
int result2 = (*ptrToFunc) (12, ’a’); // C

MyClass instance1= new MyClass;
int result3 = (instance1.*ptrToMember)(12, ’a’); // C++
//call from inside member function
int result4 = (*this.*ptrToMember)(12, ’a’); // C++ if this-pointer can be used
MyClass* instance2 = new MyClass;
int result4 = (instance2->*ptrToMember)(12, ’a’); // C++, instance2 is a pointer

How To Compare Function Pointers ?
We can use the comparison-operators (==, !=) the same way as usual.
Following is the example of it.
CODE

// C
if(ptrToFunc >0) // check if initialized
if(ptrToFunc == &SendIt) //compare to check whether is points to SendIt

// C++
if(ptrToConstMember >0)
if(ptrToConstMember == &MyClass::SendIt2)

How to Pass a Function Pointer as an Argument ?
We can pass a function pointer as a function’s calling argument. We need this many times
e.g. while passing a pointer to a callback function.
CODE

void PassPtr(int (*ptrToFunc)(float, char))
// This contains one parameter int (*ptrToFunc)(float,char) you can
// understand now what it is…
{
int result = (*ptrToFunc)(12, ’a’); // call using function pointer
cout << result << endl;
}
// execute code - ’SendIt’ is a suitable function as defined in above codes
void Pass_A_Function_Pointer()
{
PassPtr(&SendIt);
}

How to Return a Function Pointer ?
It’s a little bit tricky but a function pointer can be a function’s return value. Here I am giving
two ways of how to return a pointer to a function which is taking two float arguments and returns a float.
If you want to return a pointer to a member function you have just got to change the definitions/declarations
of all function pointers.
CODE

// specifies which function to return
float (*GetPtr1(int a, int b))(float, float)
//here the function is GetPtr1(int,int) and it’s return parameter is a pointer to
//function
{
if(a>b)
return &Subtract;
else
return &Add;
}

//The easier way could be :
// Solution using a typedef : Define a pointer to a function which is taking
// two floats and returns a float

typedef float(*ptrToFunc)(float, float);
//now we can use ptrToFunc as user defined datatype, see following code :

ptrToFunc GetPtr2(int a, int b)
{
if(a>b)
return &Subtract;
else
return &Add;
}

void Return_A_Function_Pointer()
{
ptrToFunc pt2Function = NULL;
pt2Function=GetPtr1(10,20); // get function pointer from function ’GetPtr1’
cout << (*pt2Function)(2, 4) << endl; // call function using the pointer
pt2Function=GetPtr2(’10,20); // get function pointer from function ’GetPtr2’
cout << (*pt2Function)(2, 4) << endl; // call function using the pointer
}

Following program will make everything clear :

QUOTE
Please check program in document


How to Use Arrays of Function Pointers ?
Operating with arrays of function pointer is very interesting. This offers the possibility to select
a function using an index. The syntax appears difficult, which frequently leads to confusion. There are two
ways of how to define and use an array of function pointers in C and C++. The first way uses a typedef, the
second way directly defines the array. It’s up to us which way we prefer.
CODE

// C
typedef int (*ptrToFunc)(float, char);
// illustrate how to work with an array of function pointers
void Array_Of_Function_Pointers()
{
// define arrays and initialise each element to NULL, <funcArr1> and <funcArr2> are arrays with 10 pointers to
//functions which return an int and take a float and a
//char
// first way using the typedef
ptrToFunc funcArr1[10] = {NULL};
// 2nd way directly defining the array
int (*funcArr2[10])(float, char) = {NULL};
// assign the function’s address
funcArr1[0] = &SendIt;
funcArr1[1] = &SendIt2;
/* more assignments */
// calling a function using an index to address the function pointer
printf("%d\n", funcArr1[1](12, ’a’)); // short form
printf("%d\n", (*funcArr1[0])(12, ’a’)); // "correct" way of calling
}

// C++
// type-definition:
typedef int (MyClass::*ptrToMember)(float, char);
void Array_Of_Member_Function_Pointers()
{
// arrays with 10 pointers to member functions which return an int and take
// a float and a char
// first way using the typedef
ptrToMember funcArr1[10] = {NULL};
// 2nd way of directly defining the array
int (MyClass::*funcArr2[10])(float, char) = {NULL};
// assign the function’s address - ’SendIt’ and ’SendIt2’
funcArr1[0] = funcArr2[1] = &TMyClass::SendIt;
funcArr1[1] = funcArr2[0] = &TMyClass::SendIt2;
// calling a function using an index to address the member function pointer
MyClass instance;
cout << (instance.*funcArr1[1])(12, ’a’) << endl;
cout << (instance.*funcArr1[0])(12, ’a’) << endl;
}




Was that helpful huh.gif . I hope It was... sleepy.gif


Attached File(s)
Attached File  Function_Pointers.doc ( 59k ) Number of downloads: 317


Register to Make This Ad Go Away!

spullen
Group Icon



post 14 Apr, 2007 - 02:35 PM
Post #2
I am new to c++, and I think I understand what a function pointer is from your tutorial, however I still have some questions. So as the name implies a function pointer is a pointer that points to a memory location of a function, and it acts as a variable, right? So what does this mean in terms of execution time, is it quicker then a normal function because it knows exactly where in memory the instruction for the method is?

AmitTheInfinity
Group Icon



post 17 Apr, 2007 - 07:22 AM
Post #3
QUOTE(spullen @ 15 Apr, 2007 - 03:05 AM) *

So what does this mean in terms of execution time, is it quicker then a normal function because it knows exactly where in memory the instruction for the method is?


Well, function pointer may save on execution time but that is not the main purpose behind the use of function pointers. Function pointers are mainly used to get late binding, the situation where we have to decide which funtion to call at runtime.

so in case where we have 5-6 functions with same parameter list and we are supposed to call one of them with the parameters passed. This decision of calling one of these functions is dependant on the parameters which we are getting in.

the complexity rises when we are supposed to do the further execution depending on which function got called. To come over the situation we might try different ways like using variables as flags or passing values through functions. but all these options lead to nothing but more complexity.

So, we can use function pointer here. we will have one function pointer which will point to one of these function based on the input given. As I mentioned in tutorial you can even compare the function pointer with functions so you will not need to maintain which function you called runtime.

This is one of the benifits of function pointers.
Main purpose of function pointer is for callbacks or late bindings.
So whenever you use function pointer, just check that whether you really need it. [this implies to every feature of language actually biggrin.gif ]

I hope this will help you. smile.gif

spullen
Group Icon



post 29 Apr, 2007 - 10:56 AM
Post #4
hmm, that makes sense. I guess I'll get more familiar with it when I have to use it more.

Xing
Group Icon



post 4 May, 2007 - 02:44 AM
Post #5
Excellent function pointers tutorial can be found here
http://www.newty.de/fpt/index.html

spullen
Group Icon



post 8 May, 2007 - 08:29 AM
Post #6
nice find

born2c0de
Group Icon



post 8 May, 2007 - 11:15 PM
Post #7
Also note that a lot of protection mechanisms use function pointers combined with other techniques such as Stack Execution and others.

This makes reverse engineering a lot tougher.

k.sangeeth
**



post 1 Aug, 2007 - 05:25 AM
Post #8
QUOTE(Xing @ 4 May, 2007 - 02:44 AM) *

Excellent function pointers tutorial can be found here
http://www.newty.de/fpt/index.html


great link .. the world is still a good place to be ..
so many knowledgeable people and so much good will biggrin.gif


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 5/16/08 09:01AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month