0

For example, I have a given struct X. And now, I am defining additionally A, B and C. All of them contain the exact same attributes like X but contain also additional ones.
I've seen the following question: Extending a struct in C
I don't want to make use of this nested thing, also, I never use X itself. It is only a collection of attributes which appear in all other structures.
I was pondering about just defining the content of X as macro and use it in the definitions of the other structs. For example:

#ifndef
#define X                   \
    char *some_char_arr;    \
    int *some_int_arr;
#endif

struct A { 
    X
    int specific_to_a[10]; 
}

struct B { 
    X
    int specific_to_b[20];
}

struct C { 
    X
    int specific_to_c[30]; 
}

Would that be an adequate solution or is there something better? Or is there any problem with this approach?

Lavair
  • 888
  • 10
  • 21
  • So they don't actually "extend" that 'base' at all, just happen to have some of the same member variables? – underscore_d Nov 19 '19 at 12:14
  • @underscore_d yes you could phrase it like that. They only share the "same" member variables. At the end, `A`, `B` and `C` have nothing to do with each other and are used independently. – Lavair Nov 19 '19 at 12:16
  • Could you have a single struct which includes a union? – LegendofPedro Nov 19 '19 at 22:36

1 Answers1

3

While a macro like that would compile and work, it is generally considered bad practice due to readability and maintainability concerns.

The way inheritance is typically done in C is with nested structs, like in the linked answer. So you would have:

struct Base {
    char *some_char_arr;
    int *some_int_arr;
};

struct A { 
    struct Base base;
    int specific_to_a[10]; 
};

If you don't like typing a.base.some_char_arr and would rather just type a.some_char_arr you can use anonymous structs as explained here (and which is supported by C11).

mnistic
  • 10,866
  • 2
  • 19
  • 33