-6

I know this has been asked 10000 times, however, I'm still having issues getting this to compile. Notice the static member 'map'.

In the 'getMap()' function, I receive an undefined reference error referring to the map data member. I attempted to move that function to a cpp file and declare 'map' in that file. However, I then receive a conflicting definition error.

Can somebody explain to me what is going on? Thanks

Base.h

template<typename T> Base * createT() { return new T; }
typedef std::map<std::string, Base*(*)()> map_type;


class BaseFactory
{
    static Base* createInstance(std::string const& s)
    {
        map_type::iterator it = getMap()->find(s);
        if (it == getMap()->end())
            return 0;

        return it->second();
    }

protected:
    static map_type *getMap()
    {
        if (!map)
        {
            map = new map_type;
        }

        return map;
    }

private:
    static map_type * map;
     static Base* createInstance(std::string const* s);

public:
     BaseFactory();
     ~BaseFactory();

};
tier1
  • 6,303
  • 6
  • 44
  • 75
  • 2
    So in the 10001th time you missed the error message plus the actual line of code indicating the error – P0W Oct 13 '13 at 19:55
  • You misunderstood the advice you were given. The answer is not to move the function to the cpp file. The solution is to *add new code* to the cpp file. This new code defines the static member. How can such a simple thing be so difficult? – john Oct 13 '13 at 19:58
  • @john Thanks. I got this working. P.S. for everybody else, this question did not deserve the number of down votes received. – tier1 Oct 13 '13 at 20:00
  • @tkcsam put your mouse cursor, on the down arrow button, and see why it deserved that – P0W Oct 13 '13 at 20:03
  • @P0W Funny, yet not helpful. – tier1 Oct 13 '13 at 20:04

1 Answers1

0

The following declaration within a definition of your class is not enough:

private:
    static map_type * map;

In one .cpp file, you must also add:

map_type* BaseFactory::map = NULL;

This article might help you too: Static data members (C++ only)
+ this question, which has almost 100k views by now: Initializing private static members

Community
  • 1
  • 1
LihO
  • 41,190
  • 11
  • 99
  • 167
  • I didn't make my original point clear. I wanted to keep everything in the header file, but I moved your suggestion beneath the class definition and it worked. Thanks for your help. – tier1 Oct 13 '13 at 19:59
  • 1
    @tkcsam: I've edited my answer to make it more clear. – LihO Oct 13 '13 at 20:02