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

c, c++, extern-c, gcc

Solution

This is entirely legal. In C++, classes and structs are identical concepts, with the exception that all struct members are public by default. That's the only difference. So asking whether you can extend a struct is no different than asking if you can extend a class.

There is one caveat here. There is no guarantee of layout consistency from compiler to compiler. So if you compile your C code with a different compiler than your C++ code, you may run into problems related to member layout (padding especially). This can even occur when using C and C++ compilers from the same vendor.

I have had this happen with gcc and g++. I worked on a project which used several large structs. Unfortunately, g++ packed the structs significantly looser than gcc, which caused significant problems sharing objects between C and C++ code. We eventually had to manually set packing and insert padding to make the C and C++ code treat the structs the same. Note however, that this problem can occur regardless of subclassing. In fact we weren't subclassing the C struct in this case.

Problem

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++ code: ``` class bar : public foo { int my_bar() { return ret_foo( (foo)this ); } }; ``` There's an `extern "C"` around the C++ code and each code is inside its own compilation unit. Is this portable across compilers?

Original source