Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing pointer functions to emulate member functions in C structs
    primarykey
    data
    text
    <p>So just for the sake if having ''fun'' I decided to emulate <code>C++</code> member functions in <code>C</code> using pointer functions. Here is a simple code:</p> <p>obj.h:</p> <pre><code>#ifndef OBJ_H #define OBJ_H #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; struct Obj{ struct pObjVar* pVar; void (*read)(struct Obj*); void (*set) (struct Obj*, int); }; struct Obj* newObj(); void deleteObj(struct Obj** obj); #endif </code></pre> <p>obj.c:</p> <pre><code>#include "obj.h" void readValue(struct Obj* this_); void setValue (struct Obj* this_, int mValue_); struct pObjVar{ int mValue; }; struct Obj* newObj(){ struct Obj* tmp = (struct Obj*) malloc(sizeof(struct Obj)); tmp-&gt;pVar = (struct pObjVar*) malloc(sizeof(struct pObjVar)); tmp-&gt;pVar-&gt;mValue = 0; tmp-&gt;read = readValue; tmp-&gt;set = setValue; return tmp; } void deleteObj(struct Obj **obj){ free((*obj)-&gt;pVar); (*obj)-&gt;pVar = NULL; free((*obj)); *obj = NULL; } void readValue(struct Obj *this_){ printf("Value = %d\n",this_-&gt;pVar-&gt;mValue); } void setValue(struct Obj *this_, int mValue_){ this_-&gt;pVar-&gt;mValue = mValue_; } </code></pre> <p>main.c:</p> <pre><code>#include "obj.h" int main(void) { struct Obj* a = newObj(); a-&gt;set(a, 10); a-&gt;read(a); deleteObj(&amp;a); return 0; } </code></pre> <p>Output:</p> <pre><code>&gt;./a.out Value = 10 </code></pre> <p>In doing this, however, I figured I had to emulate the role of implicit <code>this</code> pointer by explicitly passing it to my member functions. This works fine, I guess, except that it makes the whole thing look weird! </p> <p>If I wanted to pass the object, why would implement the functions as member functions? The only answer I found to it was maybe in cases where you would want to have a unified interface but various implementations? (something <em>similar</em> to <code>C++</code> virtual functions?) </p> <p>What are (if any) some other reasons to emulate member functions? Also, is there any way to get around passing the explicit <code>this_</code> pointer at all?</p> <p><strong>EDIT</strong>: There was problem in the original code when passing the object. I was using <code>&amp;a</code> by mistake for the <code>read/set</code> functions. You would only need it for the <code>deleteObj</code> if you want to set the pointer to <code>NULL</code> internally.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload