Possible Duplicate:
How could one implement C++ virtual functions in C
In C++ the only difference between a class and a struct is the default access level. So you can have virtual functions in structures, inherit from structures and so on. My question is, can you also do this in C?
You can do "virtual functions" with function pointers stored in your structs. For inheratince, you can embed a struct in another struct but the syntax, again, is going to be different than what you would expect. You can write object-oriented programs in C (classic example is the unix file/socket/... API), but with a quite awkward syntax.
Relevant answers here: https://stackoverflow.com/search?q=C+virtual+functions
C has no native syntax for virtual methods. However, you can still implement virtual methods by mimicking the way C++ implements virtual methods. C++ stores an additional pointer to the function definition in each class for each virtual method. Thus, you can simply add a function pointer to a struct to simulate virtual methods.
For example
#include <stdio.h>
#include <stdlib.h>
int f2(int x)
{
printf("%d\n",x);
}
typedef struct mystruct
{
int (*f)(int);
} mystruct;
int main()
{
mystruct *s=malloc(sizeof(mystruct));
s->f=f2;
s->f(42);
free(s);
return 0;
}
No you can't. 'virtual' is not part of the C vocabulary, neither is 'access level'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With