Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - function pointers and class

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?

like image 306
Nikhil Singh Avatar asked Dec 08 '25 10:12

Nikhil Singh


1 Answers

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.

like image 143
Revolver_Ocelot Avatar answered Dec 09 '25 23:12

Revolver_Ocelot