Home > Blockchain >  Class approximation in C - Is this witchcraft or technically acceptable?
Class approximation in C - Is this witchcraft or technically acceptable?

Time:01-16

I need to do a large Project in C and C only, without external librairies (except for SDL). I started looking for ways to do some kind of class in C, what led me to that :

typedef void (*voidFunction)(void);

typedef struct{
    int id;                             
    voidFunction printId;
} Object;

Object *new_Object(int id){
    Object *newObject = malloc(sizeof(Object));
    newObject->id = id;
    void printId(){
        static Object *this = NULL;
        if(!this) this = newObject;
        printf("%d\n", this->id);
    };
    newObject->printId = printId;
    return newObject;
}

int main(){
    Object *object = new_Object(5);
    object->printId();
    object->id  ;
    object->printId();
    return 0;
}

Output of main :

5
6

So this works, but does it seems reasonable ? Should I expect a backlash if I use this kind of architecture for a big project? Maybe I'm typing out of my allocated memory without realizing it?

CodePudding user response:

Techniques for implementing polymorphism in C are long established, check this answer for instance https://stackoverflow.com/a/351745/4433969

Your implementation seems to be broken. Nested functions are non-standard extension. I also have doubts about static this variable.

CodePudding user response:

There are advantages for using a struct to organize data for bulk processing. However, the only advantage of using the function pointer rather than calling the function directly would be:

  1. To allow the function pointer to point to different functions having the same type for different instances of the object.
  2. To hide the "member" function definition from the linker. For example, the function printId could be declared as static within the module containing the definition for "constructor" new_Object.
  •  Tags:  
  • Related