15

I have a class and I want to have some bit masks with values 0,1,3,7,15,...

So essentially i want to declare an array of constant int's such as:

class A{

const int masks[] = {0,1,3,5,7,....}

}

but the compiler will always complain.

I tried:

static const int masks[] = {0,1...}

static const int masks[9]; // then initializing inside the constructor

Any idea on how this can be done?

Thanks!

5 Answers 5

29
class A {
    static const int masks[];
};

const int A::masks[] = { 1, 2, 3, 4, ... };

You may want to fixate the array within the class definition already, but you don't have to. The array will have a complete type at the point of definition (which is to keep within the .cpp file, not in the header) where it can deduce the size from the initializer.

Sign up to request clarification or add additional context in comments.

Comments

9
// in the .h file
class A {
  static int const masks[];
};

// in the .cpp file
int const A::masks[] = {0,1,3,5,7};

1 Comment

Since appending rather than prepending const also works in more complicated situations I prefer this solution.
2
enum Masks {A=0,B=1,c=3,d=5,e=7};

2 Comments

The problem with this approach is that i want to be able to use it like an array. For example call a value mask[3] and get a specific mask.
Ok. understood. you want to use litbs answer then, that's the way to do it.
2
  1. you can initialize variables only in the constructor or other methods.
  2. 'static' variables must be initialized out of the class definition.

You can do this:

class A {
    static const int masks[];
};

const int A::masks[] = { 1, 2, 3, 4, .... };

Comments

2

Well, This is because you can't initialize a private member without calling a method. I always use Member Initialization Lists to do so for const and static data members.

If you don't know what Member Initializer Lists are ,They are just what you want.

Look at this code:

    class foo
{
int const b[2];
int a;

foo():    b{2,3}, a(5) //initializes Data Member
{
//Other Code
}

}

Also GCC has this cool extension:

const int a[] = { [0] = 1, [5] = 5 }; //  initializes element 0 to 1, and element 5 to 5. Every other elements to 0.

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.