0

I am creating a linked list with self referential class in C++ and I want to have a static pointer of the type Item (Item is the class name) named "startPointer" so that when i call my static member function "free" , it can free up the memory by using Item::startPointer but i am getting an error(shown after code). Pls Help,

class Item
{
    public:
    std::string name;
    int row,column;
    int fileType;
    Item *ptr;
    static Item *startPointer;
    void setNextPointer(Item* ptr)
    {
        ptr=ptr;
    }
    Item *getNextPointer()
    {
        return ptr;
    }
    static void free()
        {
        Item *p,*temp;
        p=startPointer;
        while(p!=NULL)
        {
            temp=p;
            p=p->getNextPointer();
            delete temp;
        }
    }

};

cube.o:cube.cpp:(.text$_ZN4Item4freeEv[Item::free()]+0x8): undefined reference to `Item::startPointer'
collect2: ld returned 1 exit status

mingw32-make.exe: *** [cube.exe] Error 1

Execution terminated
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
Paramvir Singh Karwal
  • 597
  • 1
  • 10
  • 24
  • You should read about cosntructors, destructors and RAII. – Sebastian Hoffmann Jan 26 '14 at 16:43
  • possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – juanchopanza Jan 26 '14 at 16:44

1 Answers1

4

You have to define your static member like this:

Item* Item::startPointer = nullptr; // or = NULL; if your cpp version is below c++11

Write such a line in a single compilation unit (cpp file), otherwise the member is just declared.

Sebastian Hoffmann
  • 11,127
  • 7
  • 49
  • 77
  • `nullptr` with `C++11` – P0W Jan 26 '14 at 16:42
  • 2
    @P0W I think standart adaption is far enough than we can assume that one uses c++11 if not saying otherwise. IMO its better to show code how it is supposed to be written and not how it has been written before. – Sebastian Hoffmann Jan 26 '14 at 16:46