Let's say I want to create two sub-types of a type in C. For example:
typedef struct Car {
char *make;
} Car;
typedef struct Book {
char *title;
char *author;
} Book;
What are the options for doing this? I come from a python background, so am used to being able to do something like:
class Item:
pass
class Car(Item):
...
class Book(Item):
...
The only thing that comes to mind for C is doing a union
or enum
but then it seems like it will have a ton of un-used fields. For example:
typedef struct Item {
enum {Car, Book} type; // hide the class here
char *make;
char *title; // but now will have a bunch of null fields depending on `Item` type
} Item;
Or:
typedef struct Item {
union {
Car;
Book;
} item;
} Item;
What options are there to do this sort of pseudo-subclassing in C? My goal here is to be able to pass 'multiple types' to the same function, in this case Car
and Book
.