Is it legal to implement inheritance in C by casting pointers between one struct that is a subset of another rather than first member?

后端 未结 2 437
野性不改
野性不改 2021-01-03 05:18

Now I know I can implement inheritance by casting the pointer to a struct to the type of the first member of this struct.

However, purely a

2条回答
  •  难免孤独
    2021-01-03 05:49

    This is more-or-less the same poor man's inheritance used by struct sockaddr, and it is not reliable with the current generation of compilers. The easiest way to demonstrate a problem is like this:

    #include 
    #include 
    #include 
    
    struct base
    {
        double some;
        char space_for_subclasses[];
    };
    struct derived
    {
        double some;
        int value;
    };
    
    double test(struct base *a, struct derived *b)
    {
        a->some = 1.0;
        b->some = 2.0;
        return a->some;
    }
    
    int main(void)
    {
        void *block = malloc(sizeof(struct derived));
        if (!block) {
            perror("malloc");
            return 1;
        }
        double x = test(block, block);
        printf("x=%g some=%g\n", x, *(double *)block);
        return 0;
    }
    

    If a->some and b->some were allowed by the letter of the standard to be the same object, this program would be required to print x=2.0 some=2.0, but with some compilers and under some conditions (it won't happen at all optimization levels, and you may have to move test to its own file) it will print x=1.0 some=2.0 instead.

    Whether the letter of the standard does allow a->some and b->some to be the same object is disputed. See http://blog.regehr.org/archives/1466 and the paper it links to.

提交回复
热议问题