Search code examples
c++bubble-sort

Static function call not working (C++)


For some reason the following code gives a compiler error in DevC++: [Error] cannot declare member function 'static double* Sort::bubbleSort(double*, int)' to have static linkage [-fpermissive]

BubbleSort.cpp:

#include <iostream>
#include "Sort.h"

int main(int argc, char** argv) {

    double list[] = {4.0, 4.5, 3.2, 10.3, 2.1, 1.6, 8.3, 3.4, 2.1, 20.1};
    int size = 10;
    double* sortedList = Sort::bubbleSort(list, size);

    return 0;
}

Sort.h:

class Sort
{
    public: 
        static double* bubbleSort (double list[], int size);    
}
;

Sort.cpp:

#include "Sort.h"
#include <algorithm> // std::swap

static double* Sort::bubbleSort (double list[], int size)
{
    bool changed = true;

    do
    {
        changed = false;
        for (int j = 0;  j < size - 1; j++)
        {
            if (list[j] > list[j +1])
            {
                std::swap(list[j], list[j + 1]);
                changed = true;
            }
        }
    } 
    while (changed);

    return list; // return pointer to list array    
}

Essentially, I'm trying to call the bubbleSort function without creating a Sort object. The code works fine if I create an object first.

What could be causing the error?

Thanks for any suggestions.


Solution

  • The static modifier goes in Sort.h, but not in Sort.cpp.

    That's because it means two different things in the two contexts.

    When used inside a class declaration, static indicates that the method it refers to is a class method (that you should use without a object reference), rather than a instance method (that you need a object reference to invoke).

    When used inside the implementation file (i.e. outside of a class declaration), it indicates that the method it refers to should have static linkage, which means it should not be made visible from outside the object file that contains it. From an object oriented point of view, these functions are private to the file that contains them. It's pretty obvious that this cannot work if other files (which are using your class) should access the method.