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