Sign in to follow this  
saeedm

simple static question

Recommended Posts

In my class Vertex I'd like to keep a static variable std::vector<int> dists, and manipulate it from the functions in Vertex. The solutions I have found online are giving me errors (Im working in dev-c++ with Mingw/GCC). Here is what I have tried: //Vertex.h// class Vertex { private: static std::vector<int> dist; public: Vertex(int); int getDist(); }; //Vertex.cpp// Vertex::Vertex(int i) { Vertex::dist = i; } int Vertex::getDist() { return Vertex::dist; I get a linker error - undefined reference to Vertex::dists Thanks for any help

Share this post


Link to post
Share on other sites
Short answer:
In your CPP file you must put:
std::vector<int> Vertex::dist;

Long answer:
Writing "static type name;" in a header file tells the compiler that there is a static variable of called 'name' *somewhere* that it can use. But this doesn't tell it where to allocate the storage space for the variable.
You must put the above (short-answer) code in a source file, which tells the compiler which code-module the variable's storage will be located. Otherwise, as you've discovered, when the linker tries to assemble your program, it wont be able to find where that variable is supposed to be stored ;)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this