Click to See Complete Forum and Search --> : functions in a struct


lazy_cod3R
09-17-2001, 05:29 AM
is it possible for me to put functions in a struct so it can act like a class ?
If so how would i do it, or if its to much trouble a webpage with how would be fine.

Thanx in advance

Craig McPherson
09-17-2001, 05:46 AM
I'm not too sure about this, so someone please correct me if I'm wrong.

In C, it is not possible.

In C++, it is. In fact, a C++ struct is basically just a class that has a default scope of Public instead of Private. So adjust accordingly.

Niminator
09-17-2001, 06:49 AM
Craig, that is exactly correct. Structs and classes in c++ are virtually identical, with the one difference you described.

lazy_cod3R
09-17-2001, 09:20 AM
yes, i thought that a C struct was the same as a c++ one thats why when i tried putting functions in it wouldn't let me.

But i did make my C code sort of object oriented. Its a bit stupid i think but i need to make a linked list for my code so i basiclly wrote methods like

typedef struct{
void* next;
void* prev;
void* data;
}Node

SList_create()
SList_pushback(Node* N,void* Data)
etc etc...

these methods would then modify the Node struct. It sorta like only these methods can modify the data inside the struct, sort of like how the functions in a class can only modify the data in the class. Its a bit sill but it sorta works how i want it to so i guess its ok :)

jemfinch
09-17-2001, 11:03 AM
It's definitely possible to put functions into structs in C -- you just have to use a level of indirection by putting a function pointer in the struct.

Functions aren't first-class objects in either C or C++.

Jeremy

pinoy
09-17-2001, 05:55 PM
Use a function pointer. You may want to use the first parameter as a pointer to the struct itself.

e.g.

#include <stdio.h>

struct X {
int x;

void (*myfunc)(struct X*, int y);
};

void X_myfunc(struct X* self, int y)
{
self->x = y;
printf("%d\n", self->x);
}

int main(void)
{
/* create an instance */
struct X instance;
instance.myfunc = &X_myfunc;

/* call the function */
instance.myfunc(&instance, 5);
return 0;
}


If you want to use classes, use C++. Although it's possible to write "OO" in C, it's a kludge at best.


Functions aren't first-class objects in either C or C++.


You can use a functor object. Again a kludge, but one that is used by STL.

sans-hubris
09-17-2001, 06:26 PM
Yup, use a function pointer and if you want it the same for all objects of that struct type, then declare it static.