473,320 Members | 2,147 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Pointers to functions, when to use?

hi,
i currently reading a book on C++, the author just covered the topic
of pointer to functions, but never mentioned the use. if possible
could someone please tell me when to use them, why not such make the
function call without the pointer?

Thank you.
Jul 19 '05 #1
5 2081
On Mon, 01 Sep 2003 06:34:42 -0700, soni29 wrote:
hi,
i currently reading a book on C++, the author just covered the topic
of pointer to functions, but never mentioned the use. if possible
could someone please tell me when to use them, why not such make the
function call without the pointer?

Thank you.


One example (from C, but you can use it in C++)

#include <stdlib.h>

void qsort(void *base, size_t nmemb, size_t size,
int(*compar)(const void *, const void *));

Basically qsort takes as paarmeter an array of objects of some unknown
type, the size of those objects and the number of those elements in the
array. Then for the final argument: A function that knows how to compare
two elements of the array (returning a value less than zero, zero or
greater than zero depending on how the two parameters compare)

This way the qsort function doesn't have to know anything about what the
elements are. And when you wish to sort an array of something you only
have to provide a compare function instead of a complete qsort
implementation.

This is often more useful in C than in C++, because in C++ an
implementatin of qsort could define an interface (Sortable or something
like that) that the elements has to implement.

But suppose the elements you wish to sort may be out of your control (from
a library or somesuch) you can either subclass just to add the sortable
interface, or you can provide a sorting function.
regards
NPV
Jul 19 '05 #2

"soni29" <so****@hotmail.com> wrote in message
news:ca**************************@posting.google.c om...
hi,
i currently reading a book on C++, the author just covered the topic
of pointer to functions, but never mentioned the use. if possible
could someone please tell me when to use them, why not such make the
function call without the pointer?

Thank you.


That's a bit like asking 'why use a variable when you know the value is 42'.

Sometimes you want to use a function pointer variable or parameter, and have
that variable or parameter point at different functions at different times.
That way you can call the function wherever it happens to be pointing.

For example (stupid example)

void print_hello()
{
cout << "hello\n";
}

void print_goodbye()
{
cout << "goodbye\n";
}

void call_twice(void (*func)())
{
func();
func();
}

int main()
{
call_twice(print_hello);
call_twice(print_goodbye);
}

john
Jul 19 '05 #3
soni29 writes:
i currently reading a book on C++, the author just covered the topic
of pointer to functions, but never mentioned the use. if possible
could someone please tell me when to use them, why not such make the
function call without the pointer?


Consider writing a function to evaluate a definite integral and come up with
a numerical answer. The techniques used all require a function that, given
x, will evaluate f(x). The calling program provides an appropriate f(x)
function and passes a pointer to that function to the function that does the
actual evaluation. The integral solver is generalized, the calling program
allows a particular solution.
Jul 19 '05 #4
"Nils Petter Vaskinn" <no@spam.for.me.invalid> writes:
On Mon, 01 Sep 2003 06:34:42 -0700, soni29 wrote:
hi,
i currently reading a book on C++, the author just covered the topic
of pointer to functions, but never mentioned the use. if possible
could someone please tell me when to use them, why not such make the
function call without the pointer?

Thank you.


One example (from C, but you can use it in C++)

#include <stdlib.h>

void qsort(void *base, size_t nmemb, size_t size,
int(*compar)(const void *, const void *));

Basically qsort takes as paarmeter an array of objects of some unknown
type, the size of those objects and the number of those elements in the
array. Then for the final argument: A function that knows how to compare
two elements of the array (returning a value less than zero, zero or
greater than zero depending on how the two parameters compare)

This way the qsort function doesn't have to know anything about what the
elements are. And when you wish to sort an array of something you only
have to provide a compare function instead of a complete qsort
implementation.

This is often more useful in C than in C++, because in C++ an
implementatin of qsort could define an interface (Sortable or something
like that) that the elements has to implement.

[snip]

But that's not what the standard C++ library does. e.g.

#include<algorithm>
#include<cstdlib>
#include<vector>

bool gt(int lhs, int rhs){return rhs < lhs;}

int main()
{
std::vector<int> v(100);
std::generate(v.begin(), v.end(), &std::rand);
std::sort(v.begin(), v.end(), &gt);
}

Note both generate() and sort() take function pointers as parameters
(as well as anything else that supports operator()() :-)

Jul 19 '05 #5
soni29 wrote:
hi,
i currently reading a book on C++, the author just covered the topic
of pointer to functions, but never mentioned the use. if possible
could someone please tell me when to use them, why not such make the
function call without the pointer?

Thank you.


I use function pointers when parsing instructions or messages.
I can create a table of <key, function pointer> records. I scan
the key field of each record. If the key matches, I execute the
function by dereferencing the pointer. Search the web and this
newsgroup for "Factory Design Pattern".

This technique also works well with menus. You use a table of
<selection number, text, function_pointer>. Write one driver to
parse the table and print the menu. To add a new selection,
just add a new record to the table (along with a function to
process the given selection).

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Jul 19 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Alex | last post by:
Is there any problem with sending function pointers through in a variable argument list? I have a function like the following: typedef (*ptr2FuncType1)( int ); typedef (*ptr2FuncType2)( double...
9
by: Mikhail Teterin | last post by:
Hello! I'd like to have a variable of a pointer-to-function type. The two possible values are of type (*)(FILE *) and (*)(void *). For example: getter = straight ? fgetc : gzgetc; nextchar...
11
by: Satish Kumar | last post by:
Can any one give me indetail about, what are pointers? How are pointers useful in C prgramming? How do they work? i had gone through one book, i am a bit confused. Regards, Satish...
1
by: Kalyan | last post by:
Hello, The following posting was made on this newsgroup some 2 yrs ago. Is this still true with the present release of .net. Because I get the exact same exception thrown "Function pointer not...
39
by: Martin Jørgensen | last post by:
Hi, I'm relatively new with C-programming and even though I've read about pointers and arrays many times, it's a topic that is a little confusing to me - at least at this moment: ---- 1)...
15
by: Christian Christmann | last post by:
Hi, in which situations pointers to functions might be more efficient/convenient than a direct function call? In the example I've found so far, I see no advantage of using pointers to...
7
by: Erdal Mutlu | last post by:
Hi, I am trying to design a base class (interface) with two or more subclasses as follows: class A { .... virtual static A* getByName(const string x)=0 const; }
3
by: sam | last post by:
Hello whats the use of void pointers? and when they are useful (on which conditions?) Please give me example code with some explanation. Thanks in advance.
3
by: googlinggoogler | last post by:
Hi This should all be pretty standard C stuff, but I'm going to use terms like mouse callback to communicate what Im tyring to do. Basically I have my program whirling around in an infinite...
19
by: MQ | last post by:
Can someone tell me where I should use pointers and where I should use references? In his book, Stroustrup says that you should use pointers for passing arguments that are to be modified, not...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.