Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you _have_ to initialize a C++ static member variable?

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?

like image 948
Lee Netherton Avatar asked Nov 04 '10 15:11

Lee Netherton


1 Answers

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

like image 87
Klaim Avatar answered Oct 15 '22 11:10

Klaim