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:
(This code is, of course, entirely fictional. But the real code was much the same.)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; };
Anyway, I thought of doing this.
That way, I could useCode:/* 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; };
and perhaps evenCode:free(animal.p->all);
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.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); /* ... */ } }
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:
But then a cast would be required.Code:/* The void pointer method */ struct animal_t { const char *name; enum type_t type; void *p; };
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 *).Code:animal.p.cat->mice_caught; /* union method */ ((struct cat_t *)animal.p)->mice_caught; /* void pointer method */
Does anyone else have some other ideas of how to implement this quasi-inheritance? (No, I don't really want to use C++.)



LinkBack URL
About LinkBacks
) 




