I am new to C++ and come from C background.
I am currently working on a C++ project and as I am adding code, quite often I find myself asking of I should just have a set of helper routines or create a dedicated class for them.
Any suggestions on this please? I can see if there is code resuability element, or commonlaties then creating a class makes sense. But if, say, the code in a set of helper routines will be used only for a dedicated task for a single functionality only, what would I gain by putting them in classes?
I realise my question is quite abstract and perhaps vague but any suggestions/best practices would be appreciated.
Thanks.
Use classes when you are doing object-oriented programming, i.e. when there's some kind of object type being manipulated, not when you're just writing utility functions.
More specifically, when in C you'd have a
typedef struct { /*...*/ } Foo;
with assorted
Foo *make_foo();
void print_foo(FILE *, Foo const *);
// etc.
you should put the functions that operate on Foo
objects in a class Foo
instead. But when you've implemented a bunch of useful math operations that take and return only floating-point numbers, by all means, make them freestanding functions, and consider using namespaces instead of classes to group them together.
The great thing about C++ is that it doesn't force the class-based approach on you like Java does; it's not a good match for every problem domain.
It depends on the functions. If they manipulate a common set of data, it makes sense to put the data in a class, and make them members. If they're more or less independent of one another, putting them in a class is actually misleading; it suggests a relationship that doesn't exist.
At any rate, don't be afraid to use free functions when they are more appropriate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With