Leslieg
Leslieg

Reputation: 11

C++ Initialize class static data member

I have a class which has a number of static function to perform some calculation. However, before the calculation, I need to pass in a data to initialize some of the static data members. Currently I have an init(data) function and a clearResource() function which should be called before and after the use of the class. Is there a better way of doing that?

For example:

classA(){
 static int a;
 static init(int b) {
    a = b;
 }
 static functionA(){
   //perform something based on value of a;
    switch(a){
    }
 }

}

int main(){
  classA::init(5);
  classA::functionA();
 }

Thanks

Upvotes: 1

Views: 1711

Answers (5)

Moo-Juice
Moo-Juice

Reputation: 38825

I'd avoid using static members in this case.

This is your problem. You have a class that does processing on some data. That data, for whatever reason, needs to be shared across all instances of this processing class. Ok then, we have a non-static solution!

class Data : boost::noncopyable
{
public:
    Data()
    {
        // initialise all of our data.
    }; // eo ctor
}; // eo class Data

Where you instantiate this class is up to you. It could be a member of an application class that is run at start up, or part of some root. It just needs to be accessible and does not need to be static nor a singleton.

class DataProcessor
{
private:
    Data& m_Data;

public:
    DataProcessor(Data& _data) : m_Data(_data)
    {
    }; // eo ctor
}; // eo class DataProcessor

Upvotes: 1

Mihran Hovsepyan
Mihran Hovsepyan

Reputation: 11098

You can use this kind of design

class A()
{
public:
 static int a;
 static void functionA(int arg = A::a)
 {
  if(A::a != arg)
   A::a = arg;
  ...
 }
};

int A::a = 0;
int main()
{
 A::functionA();
}

Upvotes: 2

vitaut
vitaut

Reputation: 55554

Make the member functions and data non-static, initialize in a constructor and free resources in the destructor. This will guarantee the correct sequence of calls: initialize - perform operations - free resources in the client code.

Upvotes: 1

icecrime
icecrime

Reputation: 76755

Avoid using static member functions : have your constructor initialize the data and the destructor clear the resources (see RAII). If the existing class cannot be changed, implement a helper class which calls init from its constructor and clearResource from its destructor.

Upvotes: 2

Simone
Simone

Reputation: 11797

You should apply the RAII concept: see this and this questions.

Upvotes: 1

Related Questions