Thread: initializing static members

  1. #1
    Join Date
    Sep 2003

    initializing static members


    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,

    class Something  
         static int s_nValue;  
         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
    Farncombe, Surrey, England
    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.

    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, 05: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