I posted a question recently: Initialization of Static Class members.
Now please check this code:
#include
class A
{
static int o
The member obj_s
is static this means it is defined independently of the class.
The line:
int A::obj_s=0;
Not only defines its value but also defines the memory it uses.
That is why in the previous question you were getting a linker error (no space had been allocated for 'obj_s`. Now that you have added the line the compiler is defined the memory location(s) used by the object and the program now links.
Since the class is never instantiated, the constructor will be omitted at the link stage, and therefore probably so will the static member, since it is only ever referenced by the constructor.
I'm not 100% sure of the above statement. My biggest uncertainty is whether the zero-initialisation constitutes a reference.
EDIT: Scratch that. I just tested and found that gcc emits the static object into the final executable, even when it isn't used at all.
EDIT 2: It just occurred to me that if the class's methods and static member are all defined in a separate compilation unit, they will in fact be elided from the final executable. They only pop up in the test case because the linker only prunes at the compilation-unit level, not individual symbols.
EDIT 3: No, scratch even that. It seems that gcc wants to link against every .o, even those that aren't referenced directly or indirectly by main()
. You learn something new every day.
Obviously, it takes memory. And int A::obj_s=0
is exactly what it does: it defines the variable along with it's memory. In fact, when we say we defined a variable X
, that means we define a memory of sizeof(X)
, and that memory region we label as X
.
More about static members:
A::obj_s
is a static member of the class A
. And static members exist without any instance. They're not part of instances of A
.
§9.4.2/3 and 7 from the Standard,
once the static data member has been defined, it exists even if no objects of its class have been created.
Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3).
Read my complete answer here:
Do static members of a class occupy memory if no object of that class is created?