Hacker News new | past | comments | ask | show | jobs | submit login
Can you use a [C++] class in C? (thasso.xyz)
3 points by jay-barronville on Sept 3, 2023 | hide | past | favorite | 4 comments



Don’t forget that you need a c linkage function that calls NEW in order to properly construct the object and it’s members. If using malloc for c++ objects, it MUST be followed by placement new in order to properly construct. Just malloc might be ok if the object is “trivially default constructible “ but not sure, I don’t have the standard in front of me right now. The object in the article looks trivially default constructible so the program might be working fine by coincidence.


Yes, in the particular example presented in the article, the lone `malloc()` will work as expected without the placement new since the class is just being referenced as a blob of memory (i.e., it's equivalent to a simple C struct) and the members are being set individually in `make_rational()`. That said, this territory of C and C++ compatibility can become a footgun really quickly with all types of undefined behavior.


Makes sense! Great work!


Just to be clear, even though I submitted this article, I'm not the author.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: