Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static object initializer C++ [duplicate]

Tags:

c++

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?

like image 527
macroland Avatar asked Sep 24 '26 23:09

macroland


2 Answers

For this code it makes no difference to the observable behavior of the program.

Change main to call f twice instead of only once, and observe the difference -- if the variables are static then only one pair of X objects is ever created (the first time f is called), whereas if they're not static then one pair of objects is created per call.

Alternatively, change main to print something after calling f. Then observe that with static, the X objects are destroyed after main prints (the static objects live until the end of the program), whereas without static the objects are destroyed before main prints (automatic objects only live until exit from their scope, in this case the function f).

like image 140
Steve Jessop Avatar answered Sep 26 '26 11:09

Steve Jessop


The first time the function f() is hit the statics will be initialized (lazy loading). Had they not been declared static then they would be local variables and recreated every time you called function f().

All calls to f() will result in using the same x1 and x2.

like image 36
Science_Fiction Avatar answered Sep 26 '26 11:09

Science_Fiction



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!