Posted: 11/26/2014 10:41:11 AM EDT
|
When you have functions that are related to a specific struct, which do you feel is the better approach:
1. Function pointer inside the struct. Function gets invoked such as: mystruct->myfunc(mystruct, arg1, arg2); 2. Function outside the struct. I use static structs for pseudo namespacing, so it would look like this: myns.myfunc(mystruct, arg1, arg2); Might as well put generator/factory and cleanup functions in the ns as well. CoolStruct * mystruct = myns.new_CoolStruct(); |
Option #2 looks cleaner. However, option #1 makes it much easier to change the struct's related function on the fly:
typedef struct coolstruct CoolStruct; Now we can throw mystruct around like a madman and other code can safely invoke mystruct->transform(mystruct, 87) without worrying about whether the correct transform function will be used. |
|
If you are doing actual C programming and not C++, traditionally the struct has no functions encapsulated in it, so option #2 would be the expected coding style.
Yes, I realize that today's C++ compilers let you do C coding using structs like C++ classes. Call me a traditionalist. OK, after rereading what you are doing, the function pointer inside the struct does have its advantages as you are implementing something similar to C++ virtual functions. However, at that point, one has to question why you are not using C++ to start with. |
|
I should note that I jumped on the C++ bandwagon around 20 years ago.
After spending some time with Smalltalk, Eiffel, CLOS (Common LISP Object System), and a few others, my views on OO languages changed a bit and I became disenchanted with C++. If I do any OOP lately, it is usually in Python, Java, or C#. I also now favor using mix-ins/traits over inheritance and emphasize has-a instead of is-a when possible. |
|
Quoted:
I should note that I jumped on the C++ bandwagon around 20 years ago. After spending some time with Smalltalk, Eiffel, CLOS (Common LISP Object System), and a few others, my views on OO languages changed a bit and I became disenchanted with C++. If I do any OOP lately, it is usually in Python, Java, or C#. I also now favor using mix-ins/traits over inheritance and emphasize has-a instead of is-a when possible. How can you become disenchanted with C++? It's arguably the most powerful, most flexible language available. I do heavy data analysis. Most of our code is python driven C++. With this format, there isn't much you can't do. I prefer python now for anything small, but if I need to do something serious, I go to C++. Eta OP just read your username - nicely done |
Win a FREE Membership!
Sign up for the ARFCOM weekly newsletter and be entered to win a free ARFCOM membership. One new winner* is announced every week!
You will receive an email every Friday morning featuring the latest chatter from the hottest topics, breaking news surrounding legislation, as well as exclusive deals only available to ARFCOM email subscribers.