Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class vs helper routines - C++

Tags:

c++

c

oop

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.

like image 845
sw_eng Avatar asked Nov 30 '22 03:11

sw_eng


2 Answers

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.

like image 117
Fred Foo Avatar answered Dec 05 '22 13:12

Fred Foo


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.

like image 36
James Kanze Avatar answered Dec 05 '22 14:12

James Kanze