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

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

why is that so?? Isn't it enough if we declare it inside the class only??
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.
@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.)
@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?
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.

1 Comment

=0 is not needed; int A::cnt; will be initialized to 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.