I'm wondering how static member variables are typically implemented in languages like C++ and if their use affects the size of instantiated objects.
I know that a static members are shared by all instances of that class, but how is it shared? If it affects object size, would having 10 static variables add more size than 1?
I'm asking because I can think of two ways it might be implemented:
Static variables are used to keep track of information that relates logically to an entire class, as opposed to information that varies from instance to instance.
In object-oriented programming, there is also the concept of a static member variable, which is a "class variable" of a statically defined class, i.e., a member variable of a given class which is shared across all instances (objects), and is accessible as a member variable of these objects.
When a variable is declared as static, then a single copy of the variable is created and shared among all objects at the class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.
Any java object that belongs to that class can modify its static variables. Also, an instance is not a must to modify the static variable and it can be accessed using the java class directly. Static variables can be accessed by java instance methods also.
In C++, static members don't belong to the instances of class. they don't increase size of instances and class even by 1 bit!
struct A
{
int i;
static int j;
};
struct B
{
int i;
};
std::cout << (sizeof(A) == sizeof(B)) << std::endl;
Output:
1
That is, size of A
and B
is exactly same. static members are more like global objects accessed through A::j
.
See demonstration at ideone : http://www.ideone.com/YeYxe
$9.4.2/1 from the C++ Standard (2003),
A static data member is not part of the subobjects of a class. There is only one copy of a static data member shared by all the objects of the class.
$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).
As I said, static members are more like global objects!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With