I know that you generally initialize a static member variable from within a .cpp file. But my question is: why do you have to?
Here's an example:
#include <vector>
using namespace std;
class A {
public:
static vector<int> x;
};
main() {
int sz = A::x.size();
}
This gives a compiler error: undefined reference to 'A::x'
However, this:
#include <vector>
using namespace std;
class A {
public:
static vector<int> x;
};
// Initialize static member
vector<int> A::x;
main() {
int sz = A::x.size();
}
compiles and runs fine.
I can understand if I was initializing the vector using something other than the default constructor, but I'm not. I just want a vector of size 0 created. Surely, any static members will have to be allocated memory on program initialization, so why doesn't the compiler just use the default constructor?
That's not about initialization, it's about definition. Or more precisely : it's about knowing which compilation unit (.cpp) will hold the object (that have to be uniquely defined SOMEWHERE)
So, what's needed is simply to put the definition somewhere, in a unique place, that is a cpp, to let the compiler know that when the class's static object is called, it's defined there and nowhere else. (if you try to define your static in a header, each cpp including this header will have a definition, making impossible to know where it should be defined - and manually initialized if it's required for you use) .
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