Is it possible to subclass a C struct in C++ and use pointers to the struct in C code?

后端 未结 10 1069
滥情空心
滥情空心 2021-02-07 00:10

Is there a side effect in doing this:

C code:

struct foo {
      int k;
};

int ret_foo(const struct foo* f){ 
    return f.k; 
}

C++ c

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-07 01:02

    It probably will work but I do not believe it is guaranteed to. The following is a quote from ISO C++ 10/5:

    A base class subobject might have a layout (3.7) different from the layout of a most derived object of the same type.

    It's hard to see how in the "real world" this could actually be the case.

    EDIT:

    The bottom line is that the standard has not limited the number of places where a base class subobject layout can be different from a concrete object with that same Base type. The result is that any assumptions you may have, such as POD-ness etc. are not necessarily true for the base class subobject.

    EDIT:

    An alternative approach, and one whose behaviour is well defined is to make 'foo' a member of 'bar' and to provide a conversion operator where it's necessary.

    class bar {
    public:    
       int my_bar() { 
           return ret_foo( foo_ ); 
       }
    
       // 
       // This allows a 'bar' to be used where a 'foo' is expected
       inline operator foo& () {
         return foo_;
       }
    
    private:    
      foo foo_;
    };
    

提交回复
热议问题