1

I'm a Cpp beginner and couldn't understand the following:

struct A{
int i;
static int j;
}

int A::j = 20;

Here, I understood why static varible cannot be initialised inside A and it has to be initialised outised of A using scope resolution. (That is the point memory for j will be allocated and value is initialised) and j here doesn't add to the sizeof(A) as it is a static varible and has static storage for all the objects.

Consider the following script:

struct B{
int a;
const static int b = 20;
}

Here, I'm forced to initialize the value of b in the struct declaration directly. Why it is like this if static variable is of const type? If I try to define this variable outside the scope of B, then it is throwing a compiler error stating that there is a previous declaration of b. Here when the memory for b is actually allocated and why it has to be initialized within the declaration and why can't it cannot be initialized using a :: operator like normal static variable?

Mbeginner
  • 41
  • 4
  • 4
    You aren't forced to initialize the value of `b` in the declaration. `const int B::b = 20;` will work fine. I suspect you forgot to add `;` at the end of your `struct` declaration. – François Andrieux Jun 21 '17 at 18:31
  • 2
    What happens when you try to initialize `b` outside of `B`? Do you get a compiler error? What is the error? – Code-Apprentice Jun 21 '17 at 18:32
  • @FrançoisAndrieux if the static variable is of `const static` type, why can I give the value of the variable inside unlike normal `static` variable? – Mbeginner Jun 21 '17 at 18:34
  • Can you make your bottom chunk of code complete by adding the `int B::b = 20;`, or whatever you used to initialize it? – dlasalle Jun 21 '17 at 18:35
  • 2
    @Mbeginner That question has been asked here : https://stackoverflow.com/questions/9656941/why-cant-i-initialize-non-const-static-member-or-static-array-in-class – François Andrieux Jun 21 '17 at 18:35
  • Voting to close as the problem can't be reproduced. – François Andrieux Jun 21 '17 at 18:36
  • I'm so sorry everyone. I did it wrong in initlaising. Its working perfect as Francois told. – Mbeginner Jun 21 '17 at 18:46

1 Answers1

3

You misread the error. The error should be something like "you have a conflicting declaration", meaning you declared it inline const but the definition doesn't have a const. So just do this:

const int B::b = 20;