static keyword u.s ass.(2)
Post on 19-Jul-2015
28 Views
Preview:
TRANSCRIPT
Static Keyword
1
Static keyword
We have been using static keyword in our examples. What is the meaning of
static? The word refers to something that is stationary, stopped and not moveable.
What are the types of these variables, declared as static?
How can we make use of them? Static as the word implies are variables which
exist for a certain amount of time, much longer than that by ordinary automatic
variables. Let’s consider the example about the lifetime of data variables.
One of the variable types is global variable. Global variables are those that are
defined outside of main. They are written as standalone statements before main
function
int i; the variable ‘I’ is a global variable. It is not only accessible in main but also
in all the functions. They can assign some value to ‘I’ or obtain the value of ‘I’.
Global variables come into existence whenever we execute the program and the
memory is allocated for ‘I’. It exists all the time when the program is running. At
the end of the program execution, the memory will be de-allocated and returned to
the operating system. So it has a very long lifetime. We need a value which exists
for the complete execution of the program and is available in all the functions. We
use global variables. It is not a good idea to do that unless it is absolutely
necessary. The major plus point of these variables is that these are accessible from
everywhere in the program. The inconvenience is that these variables are visible in
those functions too which does not need them
The Many Meanings of the C++ “Static” Keyword
In C++, the static keyword has a lot of meanings. Let’s go over all of them
Meaning 1: Private Linkage
This one comes from C, and it lets you mark a variable as “file private”.
Static Keyword
2
Example:
static int i = 42;
void doSomething()
{
cout << i;
}
In this example, static tells the compiler to not make the variable i available from
other source files. If another file tries to use i, perhaps using the extern keyword, it
would generate a linker error (unresolved external symbol). The same concept
applies to functions whose access you want to limit to the current file.
Uses:
This is very handy for creating “file private” variables and functions. I recommend
using static for any file-only functions. This way, you can name them whatever
you like without risking a naming collision in the global namespace.
Gotchas:
Unfortunately, you can’t declare a class as static. Also, the language makes no
guarantee about the order in which static variables are initialized. In my
experience, static variables in the same file are initialized in a “sane” order, so you
can do things like this
static int i = 42;
static int j = i + 1;
Meaning 2: Function Call Spanning
This one also comes from C, and it lets you give a function-local variable a long
lifespan.
Example:
void foo()
Static Keyword
3
{
static int callCount = 0;
callCount++;
cout << "foo has been called " << callCount << " times" << endl;
}
Uses:
it’s a great way to keep track of how many times a function has been called, so it
works well for generating unique ID numbers (watch out for thread-safety!). It’s
also useful to keep track of whether a function is being called for the first time
ever, like this:
void foo()
{
static bool firstTime = true;
if(firstTime)
{
// Do something special here
firstTime = false;
}
}
Gotchas:
Static function-local variables are initialized the first time the function is called,
not before. Using these kinds of variables can often make your code not thread safe
and not re-entrant, so take care before using them. You can put static variables
within scope blocks (like inside an if or for statement). I’m not totally sure what
Static Keyword
4
the implications are, and frankly I’ve never felt the need to limit the scope of a
variable so aggressively.
Meaning 3: Per-Class Data
When you declare a class member as static, it now belongs to the class at large, and
not a particular instance.
Example:
// In the .h file:
class MyClass
{
public:
static int FavoriteNumber;
static void foo();
};
// In the .cpp file (to initialize the static variable):
int MyClass::FavoriteNumber = 42;
void MyClass::foo()
{
// can't access member variables here!
}
Uses:
Static Keyword
5
It’s very common to store class-level constants this way. You can declare class
functions as static as well, so they would be callable from anyone who has access
to your class, even if they don’t have an instance. This is handy for helper
functions. I generally like to make class functions static if they don’t need to
operate on any instance data, typically for private helper functions.
Gotchas:
Static members are initialized very early in your program’s execution, before
main() is even called actually. You also have no guarantee about the order in
which they are initialized between classes in different files. Be careful not to
initialize one static class variable from another (possibly not-yet-initialized) static
class variable. Also, you can’t access instance data from this within a static class
function (unless someone passes you a this pointer). Lastly, you have to initialize
your static class variables in your implementation (.cpp) file. Otherwise, the
compiler doesn’t know how to allocate them (see the example above).
What is the difference between a static class and a static
member variable or method?
Let's start with the memory first. Whenever a process is loaded in the RAM, we
can say that the memory is roughly divided into three areas (within that process):
Stack, Heap, and Static (which, in .NET, is actually a special area inside Heap only known as High Frequency Heap).
The static part holds the “static” member variables and methods. What exactly is
static? Those methods and variables which don't need an instance of a class to be created are defined as being static. In C# (and Java too), we use the static keyword
to label such members as static. For e.g.
class MyClass
{
public static int a;
public static void DoSomething();
}
Static Keyword
6
These member variables and methods can be called without creating an instance of the enclosing class. E.g., we can call the static method DoSomething( ) as:
MyClass.DoSomething();
We don't need to create an instance to use this static method.
Static class declarations
The static keyword in C++ is used to specify that variables will be in
memory till the time the program ends; and initialized only once. Just
like C# and Java, these variables don’t need an object to be declared to
use them.
Summary
Static methods in the C# language differ from instance methods in
both the method declarations and in the method call sites. Static
methods apply to a type, not an instance of the type they are
defined on
top related