-4

Can't print value of static int variable

I want to check the value of static variable in this context.

I am using www.codechef.com/ide as IDE : C++14 (Gcc 6.3) as the Language + Compiler.

CODE:

#include <iostream>
using namespace std;

class Demo_StaticVar
{
    public :
    static int a;

    Demo_StaticVar()
    {
      cout<<a<<endl;
    }

};

int main()
{
  Demo_StaticVar obj1;



  return 0;
}

ERROR:

/home/ptnn1S/ccl6RBkR.o: In function `main':

prog.cpp:(.text.startup+0xf): undefined reference to `Demo_StaticVar::a' collect2: error: ld returned 1 exit status

Screenshot:

enter image description here

James Z
  • 12,209
  • 10
  • 24
  • 44

2 Answers2

0
static int a;

This declares the static variable. That tells the compiler that this field exists and would be of type int. This is useful information for compiling the code.

But the variable still needs to be defined. That is some translation unit(and exactly one translation unit) needs to allocate the memory for this variable. See What is a "translation unit" in C++

For other NITs of declaration and definition check this question: What is the difference between a definition and a declaration?

As to the solution you need to add a definition as well outside the class:

int Demo_StaticVar::a;
int main(){
... 

Code link: https://ideone.com/l7ie7p

bashrc
  • 4,725
  • 1
  • 22
  • 49
  • Sir : Did you mean > A definition reserves the memory to make the variable existing. This has to happen exactly once before first access. * Note : A definition is a declaration unless: definition defines a static class data member . Kindly assist me a bit more > as for non static variable the above code is working fine . Thank you – Akshay Arora Mar 10 '18 at 09:00
  • How do you define first access? I meant exactly what I wrote. The definition should be present in exactly one translation unit (which I called module). Otherwise the linker would again complain. BTW if my post answers your posted question can you please mark it as accepted? – bashrc Mar 10 '18 at 09:05
  • Ok , Thank you for valuable assistance – Akshay Arora Mar 10 '18 at 09:23
0

Excerpt : When a data member is declared as static, only one copy of the data is maintained for all objects of the class.

Static data members are not part of objects of a given class type. As a result, the declaration of a static data member is not considered a definition.

Source : https://msdn.microsoft.com/en-us/library/b1b5y48f.aspx