Thread: static member initialisation for multiple objects

  1. #1
    Registered User
    Join Date
    Apr 2009
    Posts
    11

    static member initialisation for multiple objects

    Hey,
    I'm wondering what the best way to define the value of a static data member within a class is. The values I want to initialise the data to is the same throughout the entire life of the program, but is calculated on runtime. Currently I'm calculating this in the class constructor, but this is causing major cpu overheads when creating multiple objects of the class. Is there a better way to do this so the initialisation is only performed once? I'm either thinking I could move the calculation out of the constructor and into an initialisation function, but was hoping there was a neater way of doing this.
    Any suggestions would be hugely appreciated,
    Thanks,
    Kieran

  2. #2
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    Static Data Members should be (re)declared outside the class declaration, because the memory for it is not allocated when inside the class.
    For example..
    Code:
    class X
    {
       static int x;
    };
    int X::x = 6;

  3. #3
    Registered User
    Join Date
    Aug 2003
    Posts
    127
    Using a nest class and its constructor

    Code:
    class T
    {
    	struct unique_tag
    	{
    		const int x;
    		
    		unique_tag()
    			: x(calculate x)
    		{	
    		}
    	};
    	
    private:
    	static unique_tag unique_;
    };
    
    T::unique_tag T::unique_;
    unique_ will be initialized before initialization of T. The nest class unique_tag is used for preventing programmer invoke the initializer of x.
    Last edited by jinhao; 04-13-2011 at 11:24 PM.
    Nana C++ Library is a GUI framework that designed to be C++ style, cross-platform and easy-to-use.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Initialisation of static variables
    By DL1 in forum C Programming
    Replies: 7
    Last Post: 08-06-2008, 05:57 PM
  2. Static variables + Initialisation
    By kris.c in forum C Programming
    Replies: 2
    Last Post: 07-08-2007, 02:16 AM
  3. static member initialisation with factory pattern
    By Bench82 in forum C++ Programming
    Replies: 3
    Last Post: 09-01-2006, 04:42 PM
  4. Static member (map) / constructor initialisation problem
    By drrngrvy in forum C++ Programming
    Replies: 9
    Last Post: 12-28-2005, 12:03 PM