-1
#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?

Gunty
  • 1,841
  • 1
  • 15
  • 27
  • What is the actual problem with the code you show? Do you get build errors? Then copy-paste them (as text) into the question. Or do you get run-time errors or crashes? Do you get unexpected results? What actually happens? And what is supposed to happen? – Some programmer dude Sep 18 '22 at 08:27
  • Please take some time to refresh [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). And don't forget how to [edit] your questions. – Some programmer dude Sep 18 '22 at 08:28
  • 1
    Does this answer your question? [Undefined reference to static variable](https://stackoverflow.com/questions/14331469/undefined-reference-to-static-variable) – fabian Sep 18 '22 at 08:30
  • Voting to reopen so that it can be closed as a dupe instead of the current reason; the edit added the necessary info. – Sebastian Redl Sep 18 '22 at 08:33

1 Answers1

4

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;
The Dreams Wind
  • 8,416
  • 2
  • 19
  • 49