Question:
C++: What do static class members do for us? How do they benefit a programmer?
2011-06-12 20:29:04 UTC
C++: What do static class members do for us? How do they benefit a programmer?
Four answers:
?
2011-06-12 20:40:22 UTC
class X

{

public:

static int i;

};

int X::i = 0; // definition outside class declaration



Once you define a static data member, it exists even though no objects of the static data member's class exist. In the above example, no objects of class X exist even though the static data member X::i has been defined.



Static data members of a class in namespace scope have external linkage. The initializer for a static data member is in the scope of the class declaring the member.



You can only have one definition of a static member in a program. Unnamed classes, classes contained within unnamed classes, and local classes cannot have static data members.
deonejuan
2011-06-12 23:48:55 UTC
Just like in Java. A static class MEMBER has one and only one value no matter how many Objects you make from that class. Get that? If you make many instances of a class, change the value of a static in one of them, all instances will have the same value. Further, you don't need an instance of the class to use a static member because the static keyword causes the runtime to go ahead an init the value and put the definition upon the heap. An easy example would be window frames with a title that goes "InternalFrame 1... InternalFrame 2... and so forth because you have a static int windowcount;



Unlike java, you can put static inside of a function and that is a constant in C/c++.
2011-06-12 20:34:21 UTC
Static doesn't mean unchangeable in this case (not the same as const), just that the variable doesn't change from instance to instance. This lets a programmer easily achieve some type of global synchronization between all instances of a class.



The classic example is creating an ID that is unique for each class instance. The global ID is statically initialized to something like 0. Then as each instance is created it copies the current value of the static variable to a private id variable and then increments it so the next instance will get a different ID.
2011-06-12 20:55:53 UTC
static members will be executed before class is loading to the memory,it means first static members will execute then after class instance variable will be executing.

The priority of execution is first on static members.



Thanks


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...