static data members

This is a discussion on static data members within the C++ Programming forums, part of the General Programming Boards category; I'm writing a factory class where I need to keep track of how many of each kind of object I've ...

  1. #1
    GA ichijoji's Avatar
    Join Date
    Nov 2002
    Posts
    179

    static data members

    I'm writing a factory class where I need to keep track of how many of each kind of object I've made so far, so I through I'd use a static map to keep track of the numbers like this:
    Code:
    class Object {
    public:
        static std::map<String,int> typeCount;
    };
    std::map<String,int> typeCount;
    According to what I can remember about static members and the result of a quick search, I think that this is the right way to declare this variable. However, when I compile (using g++ 4.0.2) I get a duplicate symbol error:
    obj/main.o(.bss+0x0): multiple definition of `Object::typeCount'
    obj/object.o(.bss+0x0): first defined here
    It isn't including the file twice and all I'm doing in main is instantiating the class. Does anybody know why this is happening?
    Illusion and reality become impartiality and confidence.

  2. #2
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    I think you mean:
    Code:
    class Object {
    public:
        static std::map<String,int> typeCount;
    };
    std::map<String,int> Object::typeCount;
    Although the definition should really go in a source file or you'll get linker errors if you include the header in more than one file
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  3. #3
    GA ichijoji's Avatar
    Join Date
    Nov 2002
    Posts
    179
    That was it. I had to move the definition over into the source file. Thanks.
    Illusion and reality become impartiality and confidence.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. dynamicly adding data members to structs
    By ITAmember in forum C Programming
    Replies: 11
    Last Post: 06-01-2009, 04:26 PM
  2. uploading file to http server via multipart form data
    By Dynamo in forum C++ Programming
    Replies: 1
    Last Post: 09-03-2008, 05:36 AM
  3. LNK2001 ERROR!!! need help
    By lifeafterdeath in forum C++ Programming
    Replies: 7
    Last Post: 05-27-2008, 06:05 PM
  4. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  5. Linking errors with static var
    By Elysia in forum C++ Programming
    Replies: 8
    Last Post: 10-27-2007, 06:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21