Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual functions in C [duplicate]

Tags:

c

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?

like image 742
Luchian Grigore Avatar asked Jul 27 '11 12:07

Luchian Grigore


3 Answers

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

like image 81
Karoly Horvath Avatar answered Nov 06 '22 07:11

Karoly Horvath


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;
}
like image 7
Jack Edmonds Avatar answered Nov 06 '22 09:11

Jack Edmonds


No you can't. 'virtual' is not part of the C vocabulary, neither is 'access level'

like image 5
Vinicius Kamakura Avatar answered Nov 06 '22 07:11

Vinicius Kamakura