| Author: Ritesh N. Jain 29 Aug 2008 | Member Level: Gold | Rating: Points: 3 |
Static variable always keep one copy of it self throughout the project,so in case you want Class specific value than use Public variable rather than using Static variable.
|
| Author: P.Renupriya 29 Aug 2008 | Member Level: Silver | Rating: Points: 5 |
When a member of a class is declared static ,it can be accessed before any object of its class are created and without reference to any object. both methods and variables can be declared to be static.
variables declared as static are global variables.when objects of its class are declared no copy of a static variable is made.instead all instances of the class share the same variable.
|
| Author: Raghav 04 Sep 2008 | Member Level: Gold | Rating: Points: 6 |
Bhargavi,
it is a good question. I agree with Renupriya. The static variable in a class is global to all objects of the class. Let me give you an example.
Static member variables only exist once in a program regardless of how many class objects are defined! One way to think about it is that all objects of a class share the static variables. Consider the following program:
class Something { public: static int s_nValue; }; int Something::s_nValue = 1; int main() { Something cFirst; cFirst.s_nValue = 2; Something cSecond; std::cout << cSecond.s_nValue; return 0; }
This program produces the following output: 2
Because s_nValue is a static member variable, s_nValue is shared between all objects of the class. Consequently, cFirst.s_nValue is the same as cSecond.s_nValue. The above program shows that the value we set using cFirst can be accessed using cSecond!
Although you can access static members through objects of the class type, this is somewhat misleading. cFirst.s_nValue implies that s_nValue belongs to cFirst, and this is really not the case. s_nValue does not belong to any object. In fact, s_nValue exists even if there are no objects of the class have been instantiated!
Consequently, it is better to think of static members as belonging to the class itself, not the objects of the class. Because s_nValue exists independently of any class objects, it can be accessed directly using the class name and the scope operator.
Bhargavi, I hope now your doubt is cleared about static variables
Raghav WebMaster
|
| Author: Sri Bhargavi 05 Sep 2008 | Member Level: Silver | Rating: Points: 1 |
Thanks for the response.
|