0

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...

nitish712
  • 19,504
  • 5
  • 26
  • 34

2 Answers2

3

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;
}
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • why is that so?? Isn't it enough if we declare it inside the class only?? – nitish712 Aug 25 '12 at 03:27
  • You might also think of initializing the value. Not sure if the compiler would assign a default or not. I always bet on "no" just to be sure. – Kevin Anderson Aug 25 '12 at 03:38
  • 4
    @nitish712 If the class is defined in a header, it can end up in more than one translation unit (source file). The compiler would have to pick one, arbitrarily, to hold the definition. Instead of picking one at random, it forces you to make that choice. (Technically, it may not even be able to make that choice, since traditionally the compiler only sees one source file at a time.) – John Calsbeek Aug 25 '12 at 03:38
  • @nitish712 - Please visit the link I've posted where you will find some interesting FAQs - [Why can't I initialize my static member data in my constructor's initialization list?](http://www.parashift.com/c++-faq/explicit-define-static-data-mems.html) – KV Prajapati Aug 25 '12 at 03:40
1

Inside the class static int cnt; is only declared, and need to be defined. In C++ you usually declare in your .h .hpp files and then define your static class members in your .c and .cpp files.

In your case, you need to add

int A::cnt=0; // = 0 Would be better, otherwise you're accessing an uninitialized variable.
aStranger
  • 249
  • 2
  • 5