some question about static member

Q

Qin Chen

Hi, all!
I need some experieced coder to explain what the following code will
produce, thank you!

#inlcude <iostream>
using namespace std;

class WithStatic{
static int x;
static int y;
public:
void print(void);
};
void WithStatic::print(void)
{
cout << "x = " << x << endl;
cout << "y = " << y << endl;
}
int x = 100;
int WithStatic::y = x + 1;
int WithStatic::x = 10;

int main()
{
WithStatic ws;
ws.print();
}
 
J

jeffc

Qin Chen said:
Hi, all!
I need some experieced coder to explain what the following code will
produce, thank you!

It produces a compiler error. Either you didn't try it yourself, or you
didn't cut and paste your actual code here. Is this a homework assignment?
Why do you need an instance of WithStatic?
 
T

tom_usenet

Hi, all!
I need some experieced coder to explain what the following code will
produce, thank you!

#inlcude <iostream>

#include said:
using namespace std;

class WithStatic{
static int x;
static int y;
public:
void print(void);
};
void WithStatic::print(void)
{
cout << "x = " << x << endl;
cout << "y = " << y << endl;
}
int x = 100;
int WithStatic::y = x + 1;
int WithStatic::x = 10;

int main()
{
WithStatic ws;
ws.print();
}

That code must produce:

x = 10
y = 11

This is because the initializer for a static variable is in the scope
of the class. Members of the class can be used without qualification,
and hide names from enclosing scopes to the initialization, so the "x
+ 1" refers to "WithStatic::x + 1".

Because WithStatic::x is statically initialized but WithStatic::y is
dynamically initialized (with the non-constant expression "x + 1"),
the fact that it appears before the x initialization doesn't matter -
it will still get the correct value of WithStatic::x. This is similar
to:

extern int i;
int j = i + 1; //dynamic initialization happens later
int i = 10; //static initialization happens first

Here j == 11.

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,432
Latest member
GTRNorbert

Latest Threads

Top