I am trying to impose some sort of semantic logic for the default values of method (or constructor) parameters. Here is what I have tried:
#include <iostream>
#include <vector>
class Test
{
public:
static const std::vector<int> staticVector;
Test (const std::vector<int> &x = Test::staticVector) {}
};
int main ()
{
Test x;
return 0;
}
Although staticVector is rather redundant, since C++ does not allow NULL to be passed as an instance of std::vector, I wish to avoid making redundant calls to the constructor std::vector(), so I came up with this approach…
Unfortunately, when I try to compile it, the linker throws this error:
error LNK2001: unresolved external symbol "public: static class std::vector<int,class std::allocator<int> > const Test::staticVector" (?staticVector@Test@@2V?$vector@HV?$allocator@H@std@@@std@@B)
What am I missing here?
This actually has nothing to do with the use of a default parameter. Instead, it’s a side-effect of how static variables work in C++.
Having a static object in a C++ class is a two-step process. First, you have to declare the static object, which you’ve done, but then you have to actually define it somewhere so C++ knows which translation unit should contain the one definition of that static object. You can do this by writing
somewhere in your C++ source file outside of the class. This tells C++ that your source file contains the definition of this object, which should resolve the linker error.
If you have several different source files and not just one, then you should put this line in the source file for the
Testclass rather than in the header.Hope this helps!