sorry to ask again, but what are static variables?? I dont understand what they are and they mean...
Thanks
Printable View
sorry to ask again, but what are static variables?? I dont understand what they are and they mean...
Thanks
static variables can only be accessed within one module. So if you have a variable like "static int x" declared in the file like "a.cpp". It is declared as static so you wont be able access it if it is from another source moduel like "b.cpp"
Simply:
first file:
a.cpp
-------
static int x;
x = 32;
cout<<x
second file:
b.cpp
------
cout<<x; //ERROR
---------------
SO, you cannot access x from a.cpp because it is declared as static in there
Hope that helps
:p
Also when using classes, a static member variable is one that is shared among members of the class, and must be initialised at file scope:Then static member functions, which don't have a this pointer and are not allowed to reference any non-static member variables or functions:Code:class NewClass {
public:
static int m_iShared;
};
NewClass::m_iShared = 5;
Code:class OtherClass {
public:
static int MyStaticFunction(int x) {
return x + 1;
}
};
Static variables are basically global variables scoped under classes, they are allocated when the app starts and destroyed when the app ends. The usefullness of static variables is that members functions can access them directly, private or public while only public static variables are accessible from outside, using scope operator :: Static functions are scoped similarily. Public static members aren't either directly under a global namespace keeping your code at least organized, but prefer to keep them private as often as possible. Public static members can be very usefull when creating templates too but that's another story :)
And then there is the static variable declared in a function:
The first call to this function would start with y being set to 0, and end with it as 1. The next call, it would start as 1, and end as 2. The third, it would start as 2, and end with 3, etcetera, etcetera.Code:INT myFunc(INT x)
{
static INT y = 0;
return x*y++;
}
Z.
Thanks a lot again!!Much clearer now=)