The Problem
Lets say that we have a simple class to sort a list of integers,
class Sorter {
public:
Sorter() {}
~Sorter() {}
enum class Algorithm { Bubble, Heap, Merge, Insertion };
void SetVector(const std::vector<int>& vec) { mVector = vec; }
void Sort(Algorithm algo)
{
void (Sorter:: * pfSort)() = nullptr;
switch (algo)
{
case Sorter::Algorithm::Bubble:
pfSort = &Sorter::BubbleSort;
break;
case Sorter::Algorithm::Heap:
pfSort = &Sorter::HeapSort;
break;
case Sorter::Algorithm::Merge:
pfSort = &Sorter::MergeSort;
break;
case Sorter::Algorithm::Insertion:
pfSort = &Sorter::InsertionSort;
break;
default:
std::cerr << "Invalid or Unsupported Sort Algorithm!";
break;
}
(this->*(pfSort))();
}
private:
void BubbleSort() { ... }
void HeapSort() { ... }
void MergeSort() { ... }
void InsertionSort() { ... }
private:
std::vector<int> mVector;
};
As you can see when were going to sort, we ask for a specific algorithm to use, and depending on it, we assign the function to a function pointer which at the end, we call it to search.
But the question is, why do we call the function pointer like this: (this->*(pfSort))();
and not like this: pfSort()
?