Emulating OOP in C using Function Pointers

Advertisemen

Basic OOP in C:

#include <stdio.h>

void printfn()
{
       printf("!\n");
}

struct foo
{
       void (*go)( void );
};

void setup( struct foo *FOO )
{
       FOO->go = printfn;
}

int main()
{
       struct foo f;

       setup(&f);

       f.go();

       return 0;
}

Using a more complex class, such as Cat (using multiple input parameters, the code gets a bit messy):


#include <stdio.h>

struct cat
{
       int posx,posy;
       void (*MoveTo)(struct cat *c, int x, int y);
       void (*Meow)( void );
       void (*DisplayPos)( const  struct cat *c );
};

void _meow()
{
       printf("Meow! :3\n");
}

void _moveTo(struct cat *c, int x, int y)
{
       c->posx = x;
       c->posy = y;
}

void _displayPos( const struct cat *c )
{
       printf("I am at (%d,%d).\n",c->posx,c->posy);
}

void setup( struct cat *FOO )
{
       FOO->Meow = _meow;
       FOO->MoveTo = _moveTo;
       FOO->DisplayPos = _displayPos;
}

int main()
{
       struct cat Cat;
       setup(&Cat);

       Cat.Meow();
       Cat.MoveTo(&Cat,1,5);
       Cat.DisplayPos(&Cat);
       Cat.Meow();


       return 0;
}

It would be better if the code didn't use the 'OOP':

#include <stdio.h>

struct cat
{
       int posx,posy;
};

void Meow()
{
       printf("Meow! :3\n");
}

void MoveTo(struct cat *c, int x, int y)
{
       c->posx = x;
       c->posy = y;
}

void DisplayPos( const struct cat *c )
{
       printf("I am at (%d,%d).\n",c->posx,c->posy);
}

int main()
{
       struct cat Cat;

       Meow();
       MoveTo(&Cat,1,5);
       DisplayPos(&Cat);
       Meow();

       return 0;
}
 
 Thus this is a waste of time unfortunately :c

Advertisemen

Disclaimer: Gambar, artikel ataupun video yang ada di web ini terkadang berasal dari berbagai sumber media lain. Hak Cipta sepenuhnya dipegang oleh sumber tersebut. Jika ada masalah terkait hal ini, Anda dapat menghubungi kami disini.

Tidak ada komentar:

Posting Komentar

© Copyright 2017 Game Engine Tutorial