Access static member variables

Discussion in 'C++' started by Rahul, Dec 5, 2007.

  1. Rahul

    Rahul Guest

    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?
    Rahul, Dec 5, 2007
    #1
    1. Advertising

  2. 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
    Victor Bazarov, Dec 5, 2007
    #2
    1. Advertising

  3. Rahul

    red floyd Guest

    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
    red floyd, Dec 5, 2007
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Markus Dehmann
    Replies:
    5
    Views:
    2,688
    red floyd
    Jul 1, 2004
  2. Siemel Naran
    Replies:
    4
    Views:
    807
    Micah Cowan
    Jan 12, 2005
  3. tom
    Replies:
    3
    Views:
    431
    dasjotre
    Nov 17, 2006
  4. dolphin
    Replies:
    3
    Views:
    1,344
    Pete Becker
    Dec 5, 2007
  5. Replies:
    9
    Views:
    946
Loading...

Share This Page