easy struct inheritance & pseudo-polymorphism vs strict aliasing

前端 未结 2 2066
一向
一向 2021-01-05 14:00

If anybody answers my question, please don\'t tell me to use C++.

So, I\'m making a small library in C that uses an object-oriented approach. I chose to use

2条回答
  •  余生分开走
    2021-01-05 14:24

    I don't think your idea about casting via char* is valid. The rule is:

    An object shall have its stored value accessed only by an lvalue expression that has one of the following types

    A sub-expression of your expression is compatible but the overall expression isn't compatible.

    I think the only realistic approach is composition:

    struct base {
      int a;
      int b;
      char c;
    
      void (*virtual_method)(base*/*this*/,int, char);
    
    };
    
    struct derived {
        struct base;
        unsigned int d;
    };
    

    I realize that's an intellectually unappealing way to achieve inheritance.

    PS: I haven't put your virtual member function pointer in my derived class. It needs to be accessible from base so needs to be declared there (assuming it's a polymorphic function that exists for both base and derived). I've also added a this parameter to flesh out the model a touch.

提交回复
热议问题