Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions in structure

Tags:

c

function

struct

Can structures contain functions?

like image 226
Shweta Avatar asked Nov 19 '10 06:11

Shweta


People also ask

What are functions of structures?

Function-structures are used to move from abstract, socioeconomic notions of intended behavior to representations tied closely to physical behavior. Reverse engineering provides a base of decomposed 'behavior-in-context', — a set of building blocks that leads directly to parts whose physical behavior can be predicted.

Can there be functions in structure?

Member functions inside the structure: Structures in C cannot have member functions inside a structure but Structures in C++ can have member functions along with data members.


1 Answers

No, but they can contain function pointers.

If your intent is to do some form of polymorphism in C then yes, it can be done:

typedef struct {     int (*open)(void *self, char *fspec);     int (*close)(void *self);     int (*read)(void *self, void *buff, size_t max_sz, size_t *p_act_sz);     int (*write)(void *self, void *buff, size_t max_sz, size_t *p_act_sz);     // And data goes here. } tCommClass; 

The typedef above was for a structure I created for a general purpose communications library. In order to initialise the variable, you would:

tCommClass *makeCommTcp (void) {     tCommClass *comm = malloc (sizeof (tCommClass));     if (comm != NULL) {         comm->open  = &tcpOpen;         comm->close = &tcpOpen;         comm->read  = &tcpOpen;         comm->write = &tcpWrite;     }     return comm; }  tCommClass *makeCommSna (void) {     tCommClass *comm = malloc (sizeof (tCommClass));     if (comm != NULL) {         comm->open  = &snaOpen;         comm->close = &snaOpen;         comm->read  = &snaOpen;         comm->write = &snaWrite;     }     return comm; }  tCommClass *commTcp = makeCommTcp(); tCommClass *commSna = makeCommSna(); 

Then, to call the functions, something like:

// Pass commTcp as first params so we have a self/this variable //   for accessing other functions and data area of object. int stat = (commTcp->open)(commTcp, "bigiron.box.com:5000"); 

In this way, a single type could be used for TCP, SNA, RS232 or even carrier pidgeons, with exactly the same interface.

like image 72
paxdiablo Avatar answered Oct 02 '22 15:10

paxdiablo