If I have the following structure defined:
typedef struct bear_t {
char* name;
void (*eat)(struct bear_t* this);
void (*drink)(struct bear_t* this);
void (*sleep)(struct bear_t* this);
void (*study)(struct bear_t* this);
void (*live)(struct bear_t* this);
void (*dtor)(struct bear_t* this);
int health;
int happiness;
} bear_t;
In a bear_t* create_bear(void) method, I want to do the following:
How would I initialize the functions?
There is nothing particularly complicated about initializing function pointers:
void eat_fish(struct bear_t* this)
{
this->happiness += 42;
this->health += 23;
}
void drink_water(struct bear_t* this)
{
this->happiness += 10;
this->health += 12;
}
// ....
bear_t* create_bear(void)
{
bear_t *bear = (bear_t*)malloc(sizeof(bear_t));
bear->name = "bear";
bear->eat = &eat_fish;
bear->drink = &drink_water;
bear->sleep = &sleep_lots;
bear->live = &live;
bear->study = NULL;
bear->dtor = &delete_bear;
bear->health = 0;
bear->happiness = 0;
return bear;
}
As a side note, please not that this kind of Object-Oriented coding in plain C-style is really not a simple way to do things. If you're actually trying to get into C++ (as the tags to the question would suggest), try sticking to the "ordinary" way of doing these kinds of things, which would be using (virtual) member functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With