2

The problem I'm facing in C is that I'd like to have a series of structs that have a base member from another struct. e.g.

struct foo {
    int a;
    void (*calculate)(struct foo *);
};
struct bar {
    int a;
    void (*calculate)(struct foo *);
    double b;
};
void do_thing(struct foo *a)
{
    a->calculate(a);
}

The problem I'm facing is that the following appears to violate strict aliasing rules.

void foo_calculate(struct foo *a)
{
    struct bar *b = (struct bar*)a;
}

The only way I've come up with to do this is to create a union inside struct foo that contains all the structs that inherit from it. Is there an easier way to accomplish this?

12
  • Does the previously mentioned thread help you? Commented Jan 14, 2016 at 23:56
  • @KennyMeyer I have no idea how I haven't seen that question before. That was almost the exact phrase I googled. It doesn't seem to account for strict aliasing rules though. Commented Jan 14, 2016 at 23:59
  • 1
    what about this: stackoverflow.com/questions/27980925/… Commented Jan 15, 2016 at 0:01
  • also this: stackoverflow.com/questions/31477307/… Commented Jan 15, 2016 at 0:02
  • 2
    In addition to the SO question you are looking at, for an excellent article/tutorial on incomplete datatypes, encapsulation, data-hiding, dynamic linkage/late binding and object oriented approaches to dynamic data-structures, see Object Oriented Programming in ANSI-C. While it is written at, and requires, a fairly in-depth knowledge of C, it is well worth the effort requierd to digest the material. It covers a number of topics not included in most C books or tutorials. Commented Jan 15, 2016 at 0:17

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.