Derived classes in C - What is your favorite method?

后端 未结 9 1250
既然无缘
既然无缘 2020-12-17 04:10

In my experience in object oriented C programming I have seen two ways to implement derived classes.


First Method, have a definition of the pa

9条回答
  •  一生所求
    2020-12-17 04:36

    Second option forces you to write very long names like myobj.parent.grandparent.attribute, which is ugly. First option is better from syntax point of view, but it is a bit risky to cast child to parent - I'm not sure whether is is guaranteed by standard that different structs will have same offsets for similar members. I guess compiler may use different padding for such structs.

    There is another option, if you are using GCC - anonymous struct members, which is part of MS extension, so I guess it was originated by some MS compiler and still may be supported by MS.

    Declarations look like

    struct shape {
        double  (*area)(struct shape *);
        const char    *name;
    };
    
    struct square {
        struct shape;           // anonymous member - MS extension
        double          side;
    };
    
    struct circle {
        struct shape;           // anonymous member - MS extension
        double          radius;
    };
    

    In your "constructor" function you need to specify correct function for calculating area and the enjoy the inheritance and polymorphism. The only problem that you always need to pass explicit this - you cannot just call shape[i]->area().

    shape[0] = (struct shape *)new_square(5);
    shape[1] = (struct shape *)new_circle(5);
    shape[2] = (struct shape *)new_square(3);
    shape[3] = (struct shape *)new_circle(3);
    
    for (i = 0; i < 4; i++)
        printf("Shape %d (%s), area %f\n", i, shape[i]->name,
                shape[i]->area(shape[i]));    // have to pass explicit 'this'
    

    Compile with gcc -fms-extensions. I never used it in real-life project but I tested it some time ago and it worked.

提交回复
热议问题