While I was trying to compile this piece of code to implement the concept of function pointer using classes in C++:
#include <iostream>
using namespace std;
class sorting
{
public:
void bubble_sort(int *arr, int size, bool (*compare)(int,int))
{
int i,j,temp = 0;
for(i = 0; i < size - 1; i++)
{
for(j = i+1; j < size; j++)
{
if(compare(arr[i],arr[j]))
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
bool ascending(int x,int y)
{
return x > y;
}
bool descending(int x,int y)
{
return x < y;
}
void display(int *arr,int size)
{
for(int index = 0; index < size; index++)
{
cout<<"arr["<<index<<"]:"<<arr[index]<<endl;
}
}
};
int main()
{
int arr[10] = {99,77,22,33,88,55,44,66,11,100};
sorting s;
cout<<"Ascending order"<<endl;
s.bubble_sort(arr,10,&sorting::ascending);
s.display(arr,10);
cout<<"Descending order"<<endl;
s.bubble_sort(arr,10,&sorting::descending);
s.display(arr,10);
return 0;
}
I got errors in these lines:
s.bubble_sort(arr,10,&sorting::ascending);
s.bubble_sort(arr,10,&sorting::descending);
The errors are:
error C2664: 'sorting::bubble_sort' : cannot convert parameter 3 from 'bool (__thiscall sorting::* )(int,int)' to 'bool (__cdecl *)(int,int)'
for both the lines. Can somebody help me to eliminate these errors?
ascending and descending are member function, therefeore they can only be called on sorting class member (and actually have three arguments, not two).
Make them static functions, or, even better, change sorting from class to namespace: there is no reason for it to be a class.
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