YiFei YiFei - 11 months ago 90
C Question

Is it safe to inherit a C struct in C++ and pass it back into a C library?

I want to, basically, inherit a C struct in C++ (while literally). I have:

struct foo { // C-side definition
int sz;
/* whatever */
// no virtual destructor, special mechanism
};

class cxx_class {
/* something here */
// no virtual destructor, no need
};

class derived : public foo /*, public cxx_class */ {
/* some other stuff here */
};


derived
instances (in form of
foo*
) will be passed back to the external library which only knows and uses the
foo
part of
derived
(of course). But the problem is that (I assume) the library uses only c-style cast, which are equivalent to
reinterpret_cast
in C++, the
foo
in
derived
must be at the beginning of the memory block.

I wonder if this is defined behavior and does standard guarantee this?




In other words:

Sometimes I use
static_cast
when I know which subclass it actually is. Is it guaranteed that
static_cast
always gives the same result as
reinterpret_cast
?

hvd hvd
Answer Source

derived instances (in form of foo*) will be passed back to the external library which only knows and uses the foo part of derived (of course).

If your functions take a foo*, it doesn't matter. Even if constructing your types in such a way that foo is not placed at the beginning of derived, the conversion from derived* to foo* happens in the C++ code which does know about the type layout. The external function then doesn't need to worry about it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download