initializing static members

This is a discussion on initializing static members within the C++ Programming forums, part of the General Programming Boards category; Hello, Compiling with GCC I am wondering why I have to declare the static value outside the class, even though ...

  1. #1
    UK2
    Join Date
    Sep 2003
    Posts
    112

    initializing static members

    Hello,

    Compiling with GCC

    I am wondering why I have to declare the static value outside the class, even though I have declared it inside the class.

    I understand that static members belong to the class and not the object created by the class. And private static members can only be accessed from static functions. However, it seems like I am declaring the s_nValue twice.

    Can anyone explain why this is.

    Many thanks,

    Code:
    class Something  
    {  
     private:  
         static int s_nValue;  
     public:  
         static int GetValue() { return s_nValue; }  
     };  
       
    int Something::s_nValue = 1; // initializer  
       
    int main()  
    {  
         std::cout << Something::GetValue() << std::endl;  
    }

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    A static member variable only exists ONCE - it is essentially a global variable except for it not being visible outside of the class. Since the compiler can't really decide on it's own where it should be initialized [order of initialization of gloabl objects is somewhat "magical" anyways, without the compiler making it more difficult to see].

    So you need to put a line somewhere in the code to tell the compiler where you want that variable to be initialized.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

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, 04:42 PM
  5. Using private class members in static functions
    By sethjackson in forum C++ Programming
    Replies: 2
    Last Post: 09-23-2005, 09:54 AM

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