3 ms·
That's a valid point. This is the reason why some C API (like the chipmunk physic engine), offer two versions of constructor functions: one that allocates the
by guillaumec 12y ago
That's a valid point. This is the reason why some C API (like the chipmunk physic engine), offer two versions of constructor functions: one that allocates the memory, and one that takes an already allocated pointer.
- sparkie 12y agoI also think that asking the user to allocate memory is bad (for OOP) design, because it is leaking information which should be encapsulated into the class. How does the user even know how, or what to allocate in order to work with your "methods"? A constructor taking a pointer serves a useful purpose - it's the equivalent of a copy constructor. However, one thing you missed from the examples (quite possibly for simplification of the blog post), is that "proper" OOP design in C is done by having opaque data types in headers, with their fields only in the implementation file - the "methods" you expose in a header all take a pointer to the opaque struct as their first argument, other than the constructor, which returns one. This is how you provide the encapsulation of classes, equivalent to private fields, if you like - which should generally be the case for non-PODS.
- cousin_it 12y agoYosefk noted that this idiom in C doesn't require you to recompile all clients when you add a private field, so in some sense it gives you better encapsulation than OOP in C++.
- angersock 12y agoI also think that asking the user to allocate memory is bad (for OOP) design, because it is leaking information which should be encapsulated into the class. How does the user even know how, or what to allocate in order to work with your "methods"? What? Gods no! The user knows more about their runtime environment than your objects--indeed, consider this a form of DI for memory management. Libraries that don't let me override allocations, file access, and logging are very, very bad.
- sparkie 12y agoIn that case you would inject a function pointer to an allocator (and deallocator), however, the object constructor is the only thing which knows how to allocate the object - consider the jagged array example I gave, or even a linked list - the user has no idea how they're allocated if given just an opaque pointer.