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?