static variable:declare and define

L

linq936

Hi,
I am confused at static variable in declaring and defining.

I have the following code in header file,

class c0;

class c1 {
static std::vector<c0> cs;
};

And in C file, I operate on c1::cs in some function. But VC7 compiler
complains that c1::cs is not initialized.

I have to add the following line to the top of the C code,
std::vector<c0> c1::cs;
Then it works.

This makes half sense to me. Static variable must be defined in
addition to declaring. But how come the above newly statement does the
definition? Is that because std::vector does some dummy initialization?

Then I have another header file,
class MyString {...};

static MyString myStr; // This variable does not belong to any
class

Then in the C file when I have
myStr = "";
The compiler complains that I am re-defining myStr.

I wonder what is going on? Because myStr is a standalone variable, so
its definition is defferent from class member?
 
V

Victor Bazarov

I am confused at static variable in declaring and defining.

I have the following code in header file,

class c0;

class c1 {
static std::vector<c0> cs;

That's the declaration.
};

And in C file, I operate on c1::cs in some function. But VC7 compiler
complains that c1::cs is not initialized.

I have to add the following line to the top of the C code,
std::vector<c0> c1::cs;

That's the definition.
Then it works.

This makes half sense to me. Static variable must be defined in
addition to declaring.

Static member variables must. And only if they are of non-integral type
and are used outside the class itself.
But how come the above newly statement does the
definition?

Because it's outside of the class, at the namespace level.
Is that because std::vector does some dummy
initialization?

Nope. It's because the rules require it.
Then I have another header file,
class MyString {...};

static MyString myStr; // This variable does not belong to any
class

Then it's not a _member_, is it?
Then in the C file when I have
myStr = "";
The compiler complains that I am re-defining myStr.

Huh? You must be including the header in more than one translation unit
and that introduces multiple _definitions_ in your program.
I wonder what is going on? Because myStr is a standalone variable, so
its definition is defferent from class member?

Yep. You got it!

V
 

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

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top