Why can I not push an instance of Foo into a static vector stored inside Foo?

Viewed 49
#include <string>
#include <vector>
using namespace std;
class Foo {
public:
    string name = "Guntr";
    static vector<Foo> names;
};

int main() {
    Foo myName = Foo();
    Foo::names.push_back(myName);
}

Why can I not push an instance of Foo into a static vector stored inside Foo?

I get the following compile error:

C:\Program Files\JetBrains\CLion 2022.2\bin
\mingw\bin/ld.exe: CMakeFiles/untitled6.dir/main.cpp.obj:main.cpp:
(.rdata$.refptr._ZN3Foo5namesE[.refptr.
_ZN3Foo5namesE]+0x0): undefined reference to `Foo::names'

Is the compiler unable to determine how much memory to allocate the vector<Foo> names array?

Because the compiler is unhappy with this approach, would it be better to have the vector be a global or be stored in a driver class?

1 Answers

The problem here is that your static variable is undefined. Member variables have external linkage, so you have to define it somewhere outside of the class definition:

class Foo {
public:
    string name = "Guntr";
    static vector<Foo> names;
};

vector<Foo> Foo::names;
Related