Search code examples
c++static-functions

C++ static functions and variables


I have written a class as shown below:

#include<iostream>
using namespace std;
class A
{
static int cnt;
static void inc()
{
cnt++;  
}
int a;
public:
A(){ inc(); }
};
int main()
{
A d;
return 0;
}

I want to call the function inc through the constructor, but when i compile i am getting an error as:

/tmp/ccWR1moH.o: In function `A::inc()':
s.cpp:(.text._ZN1A3incEv[A::inc()]+0x6): undefined reference to `A::cnt'
s.cpp:(.text._ZN1A3incEv[A::inc()]+0xf): undefined reference to `A::cnt'

I am unable to understand what the error is... plz help...


Solution

  • Static field is not defined - Take a look at Why are classes with static data members getting linker errors?.

    #include<iostream>
    using namespace std;
    class A
    {
      static int cnt;
      static void inc(){
         cnt++;  
      }
      int a;
      public:
         A(){ inc(); }
    };
    
    int A::cnt;  //<---- HERE
    
    int main()
    {
       A d;
       return 0;
    }