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++?
A static member variable: • Belongs to the whole class, and there is only one of it, regardless of the number of objects. Must be defined and initialized outside of any function, like a global variable. It can be accessed by any member function of the class. Normally, it is accessed with the class scope operator.
We can access the static member function using the class name or class' objects. If the static member function accesses any non-static data member or non-static member function, it throws an error. Here, the class_name is the name of the class. function_name: The function name is the name of the static member function.
The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program. All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment).
The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With