Access static member variables

R

Rahul

Hi Everyone,

I have the following code,

class Sample
{
public: static int i;
void f()
{
Sample::i = 5;
}
};

int main()
{
Sample obj;
obj.f(); // Causes linker error saying unresolved
external symbol Sample::i...
}

It works fine, if the following statement is added before main and
after the class declaration,

int Sample::i;

Does the above statement take care of memory allocation for the
static member variable?
 
V

Victor Bazarov

Rahul said:
Hi Everyone,

I have the following code,

class Sample
{
public: static int i;
void f()
{
Sample::i = 5;

There is no need to qualify the name 'i' here, BTW.
}
};

int main()
{
Sample obj;
obj.f(); // Causes linker error saying unresolved
external symbol Sample::i...
}

It works fine, if the following statement is added before main and
after the class declaration,

int Sample::i;

Does the above statement take care of memory allocation for the
static member variable?

Yes.

V
 
R

red floyd

Rahul said:
Hi Everyone,

I have the following code,

class Sample
{
public: static int i;
void f()
{
Sample::i = 5;
}
};

int main()
{
Sample obj;
obj.f(); // Causes linker error saying unresolved
external symbol Sample::i...
}

It works fine, if the following statement is added before main and
after the class declaration,

int Sample::i;

Does the above statement take care of memory allocation for the
static member variable?

Yes. See FAQ 10.11 http://parashift.com/c++-faq-lite/ctors.html#faq-10.11
 

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,774
Messages
2,569,596
Members
45,139
Latest member
JamaalCald
Top