user3817250
user3817250

Reputation: 1043

c Implementation of Inheritance

I'm trying to figure out a good way to do semi-inheritance in c.

This is what I've come up with

//statemachine.h
...
#define CHANGE_STATE(newState)                   \
    do {                                         \
        printf("[%s]->", stateStrings[state]);   \
        state = newState;                        \
        printf("[%s]\r\n", stateStrings[state]); \
    } while (0)

.

//trafficlight.c
#include "trafficlight.h"
#include "statemachine.h"

// Is a state machine
typedef enum {
    green,
    yellow,
    red
} traffic_state;

static const char * stateStrings [] = {
    "green",
    "yellow",
    "red"
};

static traffic_state state = red;

// Move to the next signal
void lightChange(void) {
    CHANGE_STATE((state+1)%3);
}

The idea being any module that wants to be a state machine (i.e. makes use of CHANGE_STATE) must define state and stateStrings.

Just looking for feedback on this approach.

EDIT:

Question moved to codereview

Upvotes: 0

Views: 64

Answers (1)

A common way to use inheritance is to use casts, struct inside struct-s, and mimic vtables (i.e. pointers to constant struct-s containing function pointers).

Look for example inside GObject inside Glib from GTK. Read the Gobject documentation and study the many macros implementing GObject.

Upvotes: 1

Related Questions