3 ms·
Can you use a [C++] class in C?
- matt3210 3y agoDon’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.
- jay-barronville 3y agoYes, 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.
- matt3210 3y agoMakes sense! Great work!
- jay-barronville 3y agoJust to be clear, even though I submitted this article, I'm not the author.