Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Access static member variables

Reply
Thread Tools

Access static member variables

 
 
Rahul
Guest
Posts: n/a
 
      12-05-2007
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?
 
Reply With Quote
 
 
 
 
Victor Bazarov
Guest
Posts: n/a
 
      12-05-2007
Rahul wrote:
> 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
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask


 
Reply With Quote
 
 
 
 
red floyd
Guest
Posts: n/a
 
      12-05-2007
Rahul wrote:
> 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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Put variables into member variables or function variables? tjumail@gmail.com C++ 9 03-23-2008 04:03 PM
Can a static member function access non-static member? dolphin C++ 3 12-05-2007 12:39 PM
static class member - access to variables tom C++ 3 11-17-2006 12:33 PM
Can Derived class static member access protected member from base class? Siemel Naran C++ 4 01-12-2005 06:46 PM
Can't access static member var from static method. Why? Markus Dehmann C++ 5 07-01-2004 04:16 PM



Advertisments