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

后端 未结 10 1067
滥情空心
滥情空心 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:57

    Wow, that's evil.

    Is this portable across compilers?

    Most definitely not. Consider the following:

    foo* x = new bar();
    delete x;
    

    In order for this to work, foo's destructor must be virtual which it clearly isn't. As long as you don't use new and as long as the derived objectd don't have custom destructors, though, you could be lucky.

    /EDIT: On the other hand, if the code is only used as in the question, inheritance has no advantage over composition. Just follow the advice given by m_pGladiator.

提交回复
热议问题