I am trying to explore OOP in C. I am however a C n00b and would like to pick the brilliant brains of stackoverflow 🙂
My code is below:
#include <stdio.h>
#include <stdlib.h>
typedef struct speaker {
void (*say)(char *msg);
} speaker;
void say(char *dest) {
printf("%s",dest);
}
speaker* NewSpeaker() {
speaker *s;
s->say = say;
return s;
}
int main() {
speaker *s = NewSpeaker();
s->say("works");
}
However I’m getting a segfault from this, if I however remove all args from say and make it void, I can get it to work properly. What is wrong with my current code?
Also. While this implements a form of object in C, I’m trying to further implement it with inheritance, and even overriding/overloading of methods. How do you think I can implement such?
Thank You!
In your code,
NewSpeaker()doesn’t actually create a “new” speaker. You need to use a memory allocation function such asmallocorcalloc.Without assigning the value from, for example, the return value of
malloc,sis initialized to junk on the stack, hence the segfault.