Accessing static class variables in C++?


Question

Duplicate:
C++: undefined reference to static class member

If I have a class/struct like this

// header file
class Foo
{
   public:
   static int bar;
   int baz;
   int adder();
};

// implementation
int Foo::adder()
{
   return baz + bar;
}

This doesn't work. I get an "undefined reference to `Foo::bar'" error. How do I access static class variables in C++?

1
27
5/23/2017 10:29:47 AM

Accepted Answer

You must add the following line in the implementation file:

int Foo::bar = you_initial_value_here;

This is required so the compiler has a place for the static variable.

59
4/13/2009 6:46:46 AM

It's the correct syntax, however, Foo::bar must be defined separately, outside of the header. In one of your .cpp files, say this:

int Foo::bar = 0;  // or whatever value you want

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon