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

4
  • 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? Commented Sep 18, 2022 at 8:27
  • Please take some time to refresh the help pages, take the SO tour, read How to Ask, as well as this question checklist. And don't forget how to edit your questions. Commented Sep 18, 2022 at 8:28
  • 1
    Does this answer your question? Undefined reference to static variable Commented Sep 18, 2022 at 8:30
  • Voting to reopen so that it can be closed as a dupe instead of the current reason; the edit added the necessary info. Commented Sep 18, 2022 at 8:33

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.