What good is a function pointer inside a struct in c?

c, function-pointers, struct

Solution

function pointers inside structures are the base of object-programming in C (see http://www.planetpdf.com/codecuts/pdfs/ooc.pdf ). It is really really for medium-to-large C projects.

An example:

Header:

typedef struct TPile
{
    int(*Push)(struct TPile*, int);
    int(*Pop)(struct TPile*);
    void(*Clear)(struct TPile*);
    void(*Free)(struct TPile*);
    int(*Length)(struct TPile*);
    void(*View)(struct TPile*);

    int Nombre;

    struct Titem *Top;

} TPile ;

Source:

TPile TPile_Create()
{
    TPile This;
    TPile_Init(&This);
    This.Free = TPile_Free;

    return This;
}


TPile* New_TPile()
{
    TPile *This = malloc(sizeof(TPile));
    if(!This) return NULL;
    TPile_Init(This);
    This->Free = TPile_New_Free;

    return This;
}


void TPile_Clear(TPile *This)
{
    Titem *tmp;

    while(This->Top)

    {
      tmp = This->Top->prec;
      free(This->Top);
      This->Top = tmp;
    }

    This->Nombre = 0;
}

Problem

I guess using a function pointer inside a struct has something to do with encapsulating a function within a structure...? If so, then how exactly is this achieved?? And what good does it bring to have a function pointer inside a struct rather than simply defining the function?

Original source

Related problems