A. Vieira A. Vieira - 3 months ago 16
C++ Question

Setup static member object

Maybe this question has been asked around but I couldn't find it. How do I setup a static member object at its creation? And possibly perform some other tasks. The goal is to have some of it's setters called at it's creation time.

Example:

Header file A.h:

class A{

public:
A::A();
~A::A();
static QTimer updateTimer;

};


Expected implementation file A.cpp:

#include "A.h"

QTimer A::updateTimer.setInverval(100); // I need to set it's inverval to 100ms
// but only once in the beginning of it's life time

A::A(){...
}

~A::A(){...
}


So, as you can see, I would like to call 'setInverval()' function of my static object only once at it's creation and not have it called every time a new 'A' object is created.

Answer

This is what constructors are for.

If it's your own type, just write a constructor.

If the type doesn't have a constructor and you cannot modify it (like, presumably QTimer comes from Qt), then wrap it in a type of your own that does. This is a textbook case of inheritance being useful. Your wrapper class will extend the original class with a bit of new functionality: setting the interval during initialisation.

struct QTimerWrapper : QTimer
{
   QTimerWrapper(int interval)
   {
      setInterval(interval);
   }
};

struct A
{
    static QTimerWrapper updateTimer;
};

QTimerWrapper A::updateTimer(100);

Or you could use composition, having the QTimer be a member of QTimerWrapper instead.

Comments