5

I have a simple class containing a static attribute. There are two static methods in this class: one to get the static attribute and the other to initialize it. Yet when call the static method the compiler reports an error.

The class:

class Sudoku {
    Cell Grid[9][9];
    int CurrentLine;
    int CurrentColumn;

    void deleteValInColumn(int val, int col);
    void deleteValInRow(int val, int row);
    void deleteValInBox(int val, int x, int y);
    static int unsetted; //!
public:
    static void IniUnsetted() { //!
        unsetted = 0;
    }
    static int GetUns() { //!
        return unsetted;
    }
    Sudoku(ini InitGrid[9][9]);
    void Calculate_Prob_Values();
    Cell getCell(int x, int y);
    QVector<int> getPossibleValues(int x, int y);
    bool SolveIt();
};

This is the error I get:

In member function 'bool Sudoku::SolveIt()':
no return statement in function returning non-void [-Wreturn-type]
In function `ZN6Sudoku6GetUnsEv':
undefined reference to `Sudoku::unsetted` error: ld returned 1 exit status
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
Oussaki
  • 1,449
  • 2
  • 21
  • 30

4 Answers4

7

You will need to define the static variable, even if it is not initialized explicitly. That is what is missing in your code. You should have provided a simple example to reproduce the issue, but for your convenience I am providing one which works.

main.cpp

class Foo {
    public:
        static int si;
        static void bar();
};

int Foo::si = 0; // By default, it will be initialized to zero though.

void Foo::bar() {
     Foo::si = 10;
};

int main()
{
    Foo::bar();
    return 0;
}

Note: I would suggest to get someone to review your code because "unsetted" is incorrect English. If we are at it, you would probably need to fix your indentation as well.

László Papp
  • 51,870
  • 39
  • 111
  • 135
5

In your code there is no definition of unsetted, there is only declaration.

The solution is to put somewhere in your cpp file a line like this:

int Sudoku::unsetted

The reason for that is that each instantiation of Sudoku class will use the same unsetted member so it cannot be defined for each of them, so it's up to programmer to define it in one place only.

Michał Walenciak
  • 4,257
  • 4
  • 33
  • 61
2

In your cpp file, define the static variable (ideally with an initialization):

int Sudoku::unsetted = 0;
codeling
  • 11,056
  • 4
  • 42
  • 71
  • The problem is not in the initialization . the problem is in the definition it self . thank you the problem is solved . – Oussaki Dec 18 '13 at 14:14
2

If you are declaring any static variable in class, then you should define that variable outside the class also.

Example:

class A
{
    public:
    static int x;    // declaration
};

int A::x;            // definition
codeling
  • 11,056
  • 4
  • 42
  • 71
rajenpandit
  • 1,265
  • 1
  • 15
  • 21