BeeBand
BeeBand

Reputation: 11503

How can I initialise a static member of a class after certain other initialisation has taken place?

I want to be able to initialise the static member scalingfactor in the following class:

class ScalingRect: public Rect
{
public:
    static float scalingfactor;

    ...
};

I thought I'd initialise it using a static member function of another class like this in the .cpp

float ScalingRect::Rect = Engine::GetScaleFactor();

However, I don't want to call GetScaleFactor() before the Engine class is ready. How can I ensure it gets called at the right time?

Upvotes: 0

Views: 96

Answers (2)

Nim
Nim

Reputation: 33645

instead of having the static as a class member, make it a static inside a static method, and return a reference to it:

class ScalingRect: public Rect
{
public:
    static float& scalingfactor()
    {
      if (!Engine::initilized()) throw ("initilize Engine first!");
      static float value = Engine::GetScaleFactor();
      return _value;
    }

    ...
};

Now on your first call to scalingfactor() should ideally be at the end of the initiliazer for Engine, or as long as you ensure that your first call to scalingfactor() happens after the Engine initializer is completed this should work...

Upvotes: 2

Steve Townsend
Steve Townsend

Reputation: 54168

You can implement on-demand init in GetScaleFactor (with suitable guards for thread safety if needed):

float Engine::GetScaleFactor()
{
  if (!Engine::initialized())
  {
    // do the engine init here, making sure no other thread is already in progress
  }
  return scaleFactor;
}

Upvotes: 1

Related Questions