I want to create a utility class (which are usually static) and combine it with OOP's abstraction.
My question is: is it a good practice to use method hiding to combine abstraction with static, as C++ does not allow static virtual?
class Sort {
private:
static void sort(int *arr, int size);
};
class SelectSort: public Sort {
public:
static void sort(int *arr, int size);
};
class InsertSort: public Sort {
public:
static void sort(int *arr, int size);
};
So we have a Sort class that mimics Java's Interface.
-> We say: "everything that inherits Sort class should have sort() method"
-> Additionally, we do not need instances of Sorting classes, so they're made static.
Now, we can call the static utility method without creating an instance of the class, and also used abstraction.
SelectSort::sort(arr, length);
I've tried making static method virtual
class Sort {
private:
virtual static void sort(int *arr, int size);
};
And have got the following error:
error: member ‘sort’ cannot be declared both ‘virtual’ and ‘static’
Should I use method hiding or should I not bother and just pick one concept - either make sorting static or use polymorphism?
I know method hiding is not true polymorphism, but we can imitate polymorphism in cases where it is not allowed by language's semantics.
I used it for the programmer to know rather than for the compiler.
My question is more about correct design approach. My guess is that all three solutions (static, polymorphism, method hiding) are valid. But which is a more preferable approach?
Example of using std::function to be able to pass customized sort functions to another function
#include <span>
#include <vector>
#include <functional>
namespace myAlgorithms
{
void quick_sort_sort(std::span<int> data)
{
}
void bubble_sort(std::span<int> data)
{
}
} //namespace myAlgorithms
void function_using_sort_function(std::span<int> values, std::function<void(std::span<int>) sorter )
{
}
int main()
{
std::vector<int> values{5,7,4,3,1,8};
function_using_sort_function(values,myAlgorithms::bubble_sort);
}