There are at least two questions in this post. I thought it might be somewhat hard to find them amongst all of the text, so I made them green.
----
I recently wrote some code that used a union of pointers to implement a sort of inheritance:
Code:
struct cat_t {
int mice_caught;
};
struct dog_t {
int squirrels_chased;
int bones_hidden;
};
enum type_t {
ANIMAL_CAT,
ANIMAL_DOG
};
/* The union method */
struct animal_t {
const char *name;
enum type_t type;
union {
struct cat_t *cat;
struct dog_t *dog;
} p;
};
(This code is, of course, entirely fictional. But the real code was much the same.)
Anyway, I thought of doing this.
Code:
/* The union-with-void-pointer method */
struct animal_t {
const char *name;
enum type_t type;
union {
struct cat_t *cat;
struct dog_t *dog;
void *all;
} p;
};
That way, I could use
Code:
free(animal.p->all);
and perhaps even
Code:
animal.p->all = malloc(sizeof_animal(type));
size_t sizeof_animal(enum type_t type) {
switch(type) {
case ANIMAL_CAT:
return sizeof(struct cat_t);
/* ... */
}
}
But I don't know if that would be a good idea. It relys on the fact that sizeof(struct cat_t *) == sizeof(struct dog_t *) == sizeof(void *), which is probably not a good idea.
It's not really that important; I can just free() and malloc() using the right pointer. But I was wondering if this is standard and portable. Can one to rely on the sizeof() a void pointer being the same as the sizeof() a pointer to a structure?
----
As for the union of void pointers, another way of implementing it would be:
Code:
/* The void pointer method */
struct animal_t {
const char *name;
enum type_t type;
void *p;
};
But then a cast would be required.
Code:
animal.p.cat->mice_caught; /* union method */
((struct cat_t *)animal.p)->mice_caught; /* void pointer method */
I thought the first method was a little cleaner. But, of course, the second would allow free()ing and malloc()ing the data without worrying about sizeof(void *).
Does anyone else have some other ideas of how to implement this quasi-inheritance? (No, I don't really want to use C++. )