I have some class hierarchy implemented in C :
typedef struct analog_sensor analog_sens;
struct analog_sensor{
.... /*some fields*/
void (*fill_output_buf)(analog_sens *, int *);
..... /*some other fields*/
};
typedef struct {
analog_sens sensor;
void (*fill_output_buf)(analog_sens *, int *);
.../* some other fields */
}ecg_analog_sens ;
I have two analog sensors, ecg sensor and acoustic. They both fill the output buffer by calling following logic which is the same for both sensors:
void fill_output_buffer(analog_sens *sensor,
int *output_length)
{
... /* some logic copying filters output to output buffer */
....
.....
}
And then somewhere during the initialization I do the following assignments:
ecg_sens.fill_output_buf = &fill_output_buffer;
acoustic_sens.fill_output_buf = &fill_output_buffer;
Now ecg sensor has some more data to put to the output buffer, and I need to extend (override) the base fill_output_buffer
function with some more logic. So in initialization phase
of ecg instance I do the following:
void ads1299_hog_init(analog_sens *ecg_sens)
{
/* fill_output_buf function override
* This is the part I don't like, as I
* have to keep pointer to base function
* on inherited object. It will look
* very confusing for someone who will
* have to maintain the code in the future
*/
((ecg_analog_sens* )ecg_sens)->fill_output_buf = ecg_sens->fill_output_buf;
ecg_sens->fill_output_buf = ads1299_fill_output_buf;
/* fill_output_buf function override end*/
}
void ads1299_fill_output_buf(analog_sens *sens, int *output_length)
{
ecg_analog_sens *sensor = (ecg_analog_sens*) sens;
/* call parrent fill_output_buf */
/*
* This is the part I don't like, as I
* have to call the base function from
* an instance of inherited object.
* This might be very confusing for someone
* who will have to maintain the code
*/
sensor->fill_output_buf(sens, output_length);
..../*some additional logic extending the base function */
}
So when I invoke sensor->fill_output_buf(sensor, &output_length);
on ecg_sens
instance
I'm actually calling the ads1299_fill_output_buf
function. As I write in the comments above I don't like the fact that the base function is called from an inherited object. This
is too confusing. So I'm looking for some other idea or a known solution. Probably some new
keyword that might solve this better. There is this new _Generic
keyword, for example, in C11 with effect of function overload How to achieve function overloading in C? but I can't see how it can help in my situation.
Thanks.