karthik
karthik

Reputation: 17852

How to access static class variable in static member function of same class?

I provide my sample:

  class a
  {
      public:
           static int m_n;
           static  int memfuc();
  };
  int a::memfuc()
  {
        int k =m_n;
         return k;
  }

But the following sample throws linker error: unresolved external symbols

Upvotes: 1

Views: 205

Answers (4)

quamrana
quamrana

Reputation: 39414

You need to define the member m_n, but you also need to access the member correctly.

You need to add:

int a::m_n = 0  // Or some number of your choice

Now m_n is defined you can access it anywhere, not just in other member functions:

int get_m_n()
{
    int k = a::m_n;
    return k;
}

Upvotes: 0

neuro
neuro

Reputation: 15210

For a static, you have to define it as :

class a
{
    public:
       static int m_n;
       static  int memfuc();
};

int a::m_n = 0;

int main()
{
    a my_a;
}

my2c

Upvotes: 0

James
James

Reputation: 25543

You haven't defined (as opposed to declared) your static class member variable.

You could put this code in an implementation file (.cpp) somewhere:

int a::m_n = 123456;

Upvotes: 4

trojanfoe
trojanfoe

Reputation: 122458

You need to provide the implementation somewhere:

int a::m_n;

Upvotes: 2

Related Questions