Thread: initializing static stdlib containers

  1. #1
    Optics with a Twist skewray's Avatar
    Join Date
    Dec 2006
    Location
    South Pasadena, CA
    Posts
    36

    initializing static stdlib containers

    If I wanted to count how many objects of a class I make, I could write
    Code:
    // header.hh
    
    class bob
        {
        public:
            bob() ;
        private:
            static int bobCount_ ;
        }
    and then a file with the code and initialization

    Code:
    // code.cc
    
    #include "header.hh"
    
    bob::bobCount_ = 0 ;
    
    bob::bob()
        {
        bobCount_++ ;
        }
    So here is the question. Say I want to instead add each object to a stdlib set? Then my header file is

    Code:
    // header.hh
    
    #include <set>
    
    class bob
        {
        public:
            bob() ;
        private:
            static std::set<bob*> bobSet ;
        }
    and then a file with the code and initialization

    Code:
    // code.cc
    
    #include "header.hh"
    
    bob::bobSet = ????
    
    bob::bob()
        {
        bobSet.insert( this ) ;
        }
    So how do I initialize the set container class? The row of question marks doesn't work!

    Brian

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You can just write in code.cc:
    Code:
    std::set<bob*> bob::bobSet;
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Optics with a Twist skewray's Avatar
    Join Date
    Dec 2006
    Location
    South Pasadena, CA
    Posts
    36

    Thanks!

    Thanks, that definitely works. I never would have come up with the syntax, although now that I've seen it, I understand where it comes from.

    Brian

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  3. LNK2001 ERROR!!! need help
    By lifeafterdeath in forum C++ Programming
    Replies: 7
    Last Post: 05-27-2008, 05: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. [GLUT] Pointers to class methods
    By cboard_member in forum C++ Programming
    Replies: 13
    Last Post: 02-16-2006, 04:03 PM