←back to thread

218 points signa11 | 1 comments | | HN request time: 0.204s | source
Show context
throwaway7894 ◴[] No.43681266[source]
As someone who has a file with similar hacks, I will say this: I am not a C++ fan, but if you find yourself writing C code where you simulate methods via structs with function pointers often, just use C++ as a basic "C with classes" at that point. You want methods anyway, you have to go through a pointer dereference to call the function, it's just not worth the code weirdness. If you have the grit to use structs with function pointers everywhere, you have the grit to stick to the simpler subset of C++.
replies(5): >>43683169 #>>43683849 #>>43684044 #>>43701516 #>>43703558 #
ryao ◴[] No.43701516[source]
This is very bad advice for a few reasons:

1. It is not possible to add optional member functions (which would be pure virtual functions) to a C++ class base class and then check at runtime if they are unimplemented in the object (at least not without implementing some way to query the object, which is slow). If you say to handle this by having typeid checks at runtime, look at the VFS and then notice that you cannot implement this typeid check in advance, since you cannot add a typeid check for a derived class that did not even exist when you compiled your code. Thus, you still need to use structs of function pointers in C++. Maybe you can use C++ classes for some cases where structs of function pointers are used, but you would giving up the ability to implement optional functions in a sane way.

2. It ignores all of the things in C that are absent from C++. In particular, C++ refuses to support C’s variably modified types and variable length arrays, which are useful language features.

3. It ignores all of the things in C++ that you likely do not want, such as exceptions and RTTI. The requirement to typecast whenever you assign a void pointer to any other pointer is also ridiculous.

replies(2): >>43703175 #>>43703770 #
1. pjmlp ◴[] No.43703770[source]
1. There are other approaches to this with templates and concepts, and as added bonus, stronger type checking.

Thankfully regarding 2., Google went the extra mile to pay for removing them from the Linux kernel, and they were made optional C11 onwards exactly because they are an attack vector.

3. It is called stronger type safety, ridiculous is the C community still approaching computers as if writing K&R C.