Possible Duplicate:
file scope and static floats
What are static variables?
Here is a code from a book.
class X
{
int i;
public:
X(int ii = 0) : i(ii) {cout<<i<<endl;} // Default
~X() { cout << "X::~X()" << endl; }
};
void f()
{
static X x1(47);
static X x2; // Default constructor required
}
int main()
{
f();
return 0;
}
My question is why would I like to declare an object as static like in function f()? What would happen if I did not declare x1 and x2 as static?
For this code it makes no difference to the observable behavior of the program.
Change
mainto callftwice instead of only once, and observe the difference — if the variables arestaticthen only one pair ofXobjects is ever created (the first timefis called), whereas if they’re notstaticthen one pair of objects is created per call.Alternatively, change
mainto print something after callingf. Then observe that withstatic, theXobjects are destroyed aftermainprints (the static objects live until the end of the program), whereas withoutstaticthe objects are destroyed beforemainprints (automatic objects only live until exit from their scope, in this case the functionf).