-
<<split from ancient thread: https://cboard.cprogramming.com/showthread.php?t=6761>>
After a search this was the closest thread to what I'm trying to do.
Is it possible to have a function pointer in a struct that takes the same struct as it is in??
What I need it for is for a opengl app to draw objects of different types without having to use a switch to decide which drawing code to use (like a member function in C++ that calls it's own draw() routine).
eg. say I have a struct like so that is a line object that holds 2 point structs (start and end) and a draw function that uses the struct info to draw itself -
Code:
//line drawing function:
int DrawLine (Line linerecord)
{
gldrawline(linerecord);//or similar, only example.
return 0;
}
//typedef for function pointer:
typedef int (*PTR_TO_DRAW_FUNC)(Line);
// Line object struct:
typedef struct {
POINT start;
POINT end;
PTR_TO_DRAW_FUNC DrawLine;// calls 'this' drawline function.
}Line;
Then somewhere in my program I want to loop through my 'model' struct which holds records of different types of entities (circles lines etc) and calls the correct draw function for each type.
Would this work and is this the right way to go about it?
Thanks,
Mick.
-
Kind of like dynamic binding for c. You could make your 'object' hold function pointers to different function to perform different functions, but you couldn't really wouldn't reap the benefits of inheritence or anything and wouldn't be able to have like collections because the types would seem unrelated. This c-faq entry explores some options:
http://c-faq.com/struct/oop.html
http://c-faq.com/struct/oop.jxh.html
This is also a nice little publishing about object oriented c.
http://www.planetpdf.com/codecuts/pdfs/ooc.pdf
-
Thanks Tonto, I'll check those out.
Cheers,
Mick.
-
After a quick look there's plenty to think about! That ooc doc will be a good read :) thanks for the link.
Trying not to get to OO though I even thought of using a simple struct (the model) that holds an array of simple structs with a type name, a handle to its instance/record, and a pointer to a draw function to draw that type.
Perhaps that would be easier?
-
For those interested I did a bit of searching and between these two links I think I have enough tools to accomplish what I need without getting to deep in OO :)
http://sunsite.uakom.sk/sunworldonli...ol-10-ooc.html
http://www.bolthole.com/OO-C-programming.html
Cheers,
Mick.