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

后端 未结 10 1065
滥情空心
滥情空心 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条回答
  •  有刺的猬
    2021-02-07 00:53

    This is perfectly legal, and you can see it in practice with the MFC CRect and CPoint classes. CPoint derives from POINT (defined in windef.h), and CRect derives from RECT. You are simply decorating an object with member functions. As long as you don't extend the object with more data, you're fine. In fact, if you have a complex C struct that is a pain to default-initialize, extending it with a class that contains a default constructor is an easy way to deal with that issue.

    Even if you do this:

    foo *pFoo = new bar;
    delete pFoo;
    

    then you're fine, since your constructor and destructor are trivial, and you haven't allocated any extra memory.

    You also don't have to wrap your C++ object with 'extern "C"', since you're not actually passing a C++ type to the C functions.

提交回复
热议问题