Access static member variables

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Rahul

    #1

    Access static member variables

    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?
  • Victor Bazarov

    #2
    Re: Access static member variables

    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


    Comment

    • red floyd

      #3
      Re: Access static member variables

      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

      Comment

      Working...