Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing function in LL

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:

  • Create a new bear with malloc
  • Initializes the bear’s eat, drink, sleep, and live functions to the default values (eat_fish, drink_water, sleep_lots, live).
  • Initializes the study function to NULL, since default bears don’t know how to study.
  • Initializes the bear’s health and happiness to 0.
  • Initializes the bear’s destructor (dtor) field to delete_bear.
  • Sets the bear’s name to “bear” (bear->name=”bear” is sufficient).
  • Returns the bear to the caller.

How would I initialize the functions?

like image 369
Tammy Avatar asked Jul 27 '26 00:07

Tammy


1 Answers

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.

like image 105
matz Avatar answered Jul 30 '26 10:07

matz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!