4 ms·
> Using C-like structs is a very common use case Not true. Using C structs themselves in C++ is very common - when you include the C header file, the relevant
by rkangel 2y ago
> Using C-like structs is a very common use case
Not true. Using C structs themselves in C++ is very common - when you include the C header file, the relevant declarations are wrapped in "extern "C" {}" which gives structs C semantics. You can do this because C++ is backwards compatible with C.
Most of the time when you use a struct in C++ you're just ignoring most of the capabilities of objects (which is fine!). If you declare a struct in C++, you're getting an object. The only difference between the struct and class keywords in C++ is the default privacy of the members.
- gpderetta 2y agoA C++ structure has exactly the equivalent semantics of a C structure if it exists. Extern "C" only affects linkage of functions. It has no effect on structure definitions.
- OskarS 2y agoIt absolutely does not. A C++ structure is a much richer object: it can have custom copying, moving and assignment behaviours, it can have vtables, it has RAII, etc. That's the whole point about the "object model" in the article: C++ has it, C does not. What I think you're trying to say is "a POD structure with no custom behavior is essentially identical in C and C++". That is mostly true, though if the struct contains a union, C++ has stricter UB rules (there might be other differences as well, but that's the one I can think of at the moment).
- deleted 2y ago[deleted]
- gpderetta 2y agoWhat I'm saying is that extern "C" has no effect on structure compatibility.
- deleted 2y ago[deleted]