1

I have a class which is entirely static. Inside the class is a pointer to a list of integers of variable length. The functions inside the class depend on the first value in the list being initialized to 2 before they are called. Some of the functions are also called very frequently so I don't want to set that value first thing in every function.

Here is an example of the header:

class Foo{
public:
  static void f1();
private:
  static int* list;
}

and the .cpp file, globally (outside other function calls):

int* Foo::list = new int[10];

I need to initialize list[0] =2 somehow but that is not allowed in the same location as I have the list initializer.

7
  • "I have a class which is entirely static." Why? Commented Jun 8, 2015 at 19:17
  • "I need to initialize list[0] =2 somehow but that is not allowed in the same location as I have the list initializer." So? Commented Jun 8, 2015 at 19:17
  • @LightnessRacesinOrbit - Could be a base class with lots of constants. For example shape colours. Commented Jun 8, 2015 at 19:24
  • @AndyG: The initialiser can. Crucially, the initialiser is not "anybody but Foo". Commented Jun 8, 2015 at 19:48
  • I hope that static is not on your definition in real life, since it is invalid. Commented Jun 8, 2015 at 19:49

1 Answer 1

1

If your compiler supports C++ 2011 then write

int* Foo::list = new int[10] { 2 };

Another way is for example to define a private static function. For example

class Foo
{
// ...
private:
    static int *list;
    static int * init() 
    {
        int *p = new int[10];
        p[0] = 2;
        return p;
    }       
};

int* Foo::list = Foo::init();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.