Extending a struct in C

前端 未结 11 911
你的背包
你的背包 2020-12-23 15:54

I recently came across a colleague\'s code that looked like this:

typedef struct A {
  int x;
}A;

typedef struct B {
  A a;
  int d;
}B;

void fn(){
  B *b;         


        
11条回答
  •  悲&欢浪女
    2020-12-23 16:26

    I'll go out on a limb and oppose @paxdiablo on this one: I think it's a fine idea, and it's very common in large, production-quality code.

    It's basically the most obvious and nice way to implement inheritance-based object oriented data structures in C. Starting the declaration of struct B with an instance of struct A means "B is a sub-class of A". The fact that the first structure member is guaranteed to be 0 bytes from the start of the structure is what makes it work safely, and it's borderline beautiful in my opinion.

    It's widely used and deployed in code based on the GObject library, such as the GTK+ user interface toolkit and the GNOME desktop environment.

    Of course, it requires you to "know what you're doing", but that is generally always the case when implementing complicated type relationships in C. :)

    In the case of GObject and GTK+, there's plenty of support infrastructure and documentation to help with this: it's quite hard to forget about it. It might mean that creating a new class isn't something you do just as quickly as in C++, but that's perhaps to be expected since there's no native support in C for classes.

提交回复
热议问题