+ 5
What is static variable?
each and everyone says the different kind of answers about static variable.i need exact answer of static variables.
6 Respostas
+ 13
static variable belongs to a class. That is why they are called class variable.
Can be accessed immediately by classname.variablename without instantiation
+ 7
@NimWing Yuan: Totally agree. Every object of a class has a separate copy of every variable of the class. They all store different data for their respective objects, even though they are the same variables. However, in case of a static variable, there exists only a single copy for all objects of that class. If one object makes a change to its value, all objects get the updated value.
+ 3
Static versus dynamic - a concept that dates back to the earliest programming languages - defines how a variable gets assigned its location in memory.
Static means the variable does not move from its memory location. Its location gets assigned when the program loads and it remains there, affixed until the program shuts down. There is only one instance and it is globally unique. (There are technical exceptions when using virtual machines but this is the fundamental concept).
All other kinds of variables are dynamic. A dynamic variable gets assigned its location only during run time. It may be destroyed and created again as needed, each time possibly in a different location. There even will be multiple copies at the same time in different parts of memory when a class object gets instantiated multiple times.
Static necessarily disallows multiple instantiations. So beware that a static variable is a global. If multiple objects are using it, then each has potential to overwrite what another object stored there.
+ 1
If you create global variables in a file diffrent from main.cpp, you also need to make them static.
+ 1
y para los que no sabemos tanto ingles ??
0
@Gabriel I hope this is easier to read. If you wish to make sure that there is only one instance of a variable or object then you should declare that variable or object to be static. Static means that it can not move in memory and it has only one instance. Beware that if one part of the code changes the value of a static variable, then its value will be changed for all parts of the code that use it. A static object can be instantiated only once. Because it stays in one memory location it would have to overwrite itself to get instantiated again.