Question

Why isn't it correct to say that we can implement a parametric polymorphism in C programming with a void*?

Professor raised the question and never answered. I believe that a void* is actually something very low level to be considered parametric polymorphism but is there a stronger reason to that?

Was it helpful?

Solution 2

Taking this definition of parametric polymorphism:

a mechanism to explicitly or implicitly replace the type variables with concrete types when necessary.

void * does not fit.

C may do it by macros: http://rosettacode.org/wiki/Parametric_polymorphism#C

OTHER TIPS

Probably because the mechanism is "too mechanic", so much that it stops being useful in the sense that polymorphism is supposed to be useful.

Also since there's no easy way of extending a polymorphic function after the fact.

In C++, you could trivially do this:

Matrix4x4 a, b, c;

a = ...; /* Initialize matrices. */
b = ...;
c = a + b; /* Use overloaded (polymorphic) operator + to add. */

In C++, the above uses an operator+() defined in the Matrix4x4 class, and is able to determine that when compiling. So when adding the new data type, the relevant code describing how to do an add is added, re-using the existing + name. In C, you can't do that.

in C, even if you had a function

void super_add(void *sum, const void *a, const void *b);

how do you tell it about Matrix, if you just wrote the type? You would have to have some generic type-description system:

void super_add(const char *sum_type, void *sum, const char *atype, void *a, const char *btype, const void *b);

which you would have to provide some form of registration-mechanism to, so you can add new functions:

void super_add_register(const char *sum_type, const char *atype, const char *btype, void (*adder)(void *sum, const void *a, const void *b));

then you'd have to implement code to match the type names against the correct adding-function, and on and on.

In short, it's not worth it in general. Note, however, that there are libraries that do a lot of this, such as GObject.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top