Hi guys,
I'm new to object oriented programming and to gain some experience I am trying to write some programs.
My bigger concern are good manners in writing code. I was wandering if a program based on objects could have also simple functions that are no class members.
In particular my situation is the following. I want to write a library with a heap algorithm to sort an array and I want this to be more generic as possible. Is it right, in this case, to write a specific class named Heap and to construct an Heap object every time I need to sort an array? I believe it is quite illogical. Or should I write some simple functions?
Is there some way to solve this problem (I mean using classes when I feel it is not necessary) like using friendship or inheritance or some other way I don't know?
Not every problem has a [good] OOP solution. This is one reason why C++ is not strictly an OOP language.
Having loose functions is fine. And in your case it sounds like you want independent, "one-off" functions to do misc tasks and therefore do not need an entire class for them.
I would only create a Heap class if the class itself will actually represent the heap. IE: if the user will be creating a heap by instantiating that class.
But yeah... it sounds like a class is not the right solution here.
I was wandering if a program based on objects could have also simple functions that are no class members.
Yes.
Is it right, in this case, to write a specific class named Heap and to construct an Heap object every time I need to sort an array? I believe it is quite illogical. Or should I write some simple functions?
A non-member function would be more appropriate in this case, since the sorting algorithm doesn't need to maintain state in between calls to it.
Do note however that the cost of allocating on the stack an object of a class such as this:
1 2 3 4
class Heap{
public:
/*...*/ sort(/*...*/);
};
would be insignificant (on x86 just incrementing the stack pointer register, and maybe not even that). I'm not saying you should do this, I'm just saying that you shouldn't throw away a design simply because it looks inefficient at first sight.
Thank you all for the replies.
You understood my question perfectly even if I was not very clear. Thank you Duoas for the links. There are some very useful examples also in regard to the use of templates in this case.