3

wikipedia article on C states that Function and data pointers permit ad hoc run-time polymorphism.

what is the meaning of this?please explain.

Eight
  • 4,194
  • 5
  • 30
  • 51
  • possible duplicate of [How can I simulate OO-style polymorphism in C?](http://stackoverflow.com/questions/524033/how-can-i-simulate-oo-style-polymorphism-in-c) – AnT stands with Russia Jul 31 '12 at 04:53

3 Answers3

4

One of the examples that I can think of for ad-hoc polymorphism in C in qsort function. The qsort function takes a comparison function (function pointer) as input thereby allowing you to use qsort with different data types.

The prototype for qsort is as below:

void qsort(void *base, size_t nel, size_t width, int (*compar)(const void *, const void *));

The comparison function for qsort is of the form:

int (*compar)(const void *, const void *);

Pls note that the qsort function effectively provides only algorithmic implementation of the qsort algorithm leaving the data type to be used and the comparison of data types to abstracted by cleverly using function pointer for comparison function and void * for data abstraction.

qsort provides an example for abstraction of both the function and the data thereby paving way for use of ad-hoc polymorphism in C.

Jay
  • 24,173
  • 25
  • 93
  • 141
3

Examine following code:

#include <stdio.h>

typedef int (*Func)(int a, int b);
int sum(int a, int b) {
    return a + b;
}

int substruct(int a, int b) {
    return a - b;
}

int main(int argc, char** argv){
    Func f = sum;
    printf("%d\n", f(1, 2));

    f = substruct;
    printf("%d\n", f(1, 2));
}

output:

3
-1

here I demonstrated how assigning different functions to a pointer can change the behavior of a program. This is kind of polymorphism.

Ivan Kruglov
  • 743
  • 3
  • 12
2

Clearest answer I can give is to remind you that the first C++ compilers actually converted C++ code into C, and then compiled that C code into an exe.

Vestiges of this implementation are still hanging around in the notion of the "vtable" used for virtual functions - which is just a table of function pointers so the class can change the vtable in order to call a different implementation.

John3136
  • 28,809
  • 4
  • 51
  • 69