coop

'self' or 'this' reference oop functionality in PLAIN C


I'm using pseudo oop paradigm with plain c, and would like to be able to have a struct function pointer have access to the rest of the structure data.

The only way I've been able to do this is by passing the 'current object' reference in each function eg

struct MyStructure{
    //NOTE I want to access this member:
    struct MyStructure *self;
    
    int var1;
    int var2;
    
    void ( *initMemberFn    )(MyStructure *self, int arg1, int arg2);
    void ( *memberFn1       )(MyStructure *self);
    
};

void initMemberFn(MyStructure *self, int arg1, int arg2){   
    (*self).var1 = arg1;
    (*self).var2 = arg2;
    
}

void memberFn1(MyStructure *self){
    //NOTE Access the above member HERE without passing the self argument
    printf("var1:%d, var2:%d", (*self).var1, (*self).var2 );
    
}


int main(){
    
    MyStructure mystruct;
    mystruct.self = &mystruct;

    mystruct.initMemberFn = &initMemberFn;
    mystruct.memberFn1 = &memberFn1;

    mystruct.initMemberFn(mystruct.self, 1, 2);
    mystruct.memberFn1(mystruct.self);
    
}

I'll note this doesn't seem to work on all compilers but I am using visual studio's cl.exe.

Is there any (other) way I can access the structure's self member from inside one of the functions?

(I've noted the relevant lines with comments.)


Solution

  • Is there any (other) way I can access the structure's self member from inside one of the functions?

    No.

    C has no notion of object methods like C++ (or other OOP languages), only global functions.
    From the point of view of the function there is no self/this etc. unless you pass it as a parameter explicitly.
    The fact that the function is called via a function pointer stored in the struct makes no relevant difference.

    As suggested in a comment you can use a marco for making the call a bit shorter, but it will not change this basic fact, only hide it to some extent (which I personaly find less clear).

    A side note:
    In OOP languages like C++,C#, etc. it will actually under the hood be the same as in C, i.e. a pointer or reference to the current object will be passed to the function in the code generated by the compiler.