0

I have a class Phone, I want it, when created to add itself to a static collection of phones. So I have the collection:

static vector < class Phone* > instances;

And in the constructor I do this:

Phone::instances.push_back(this);

But the linker throws an unresolved external symbol, why is that? What am I doing wrong? I didn't find a similar question. Is it necessary to add the instance outside the constructor? Or do I have to have the collection on another class? Thank you very much.

2 Answers2

3

You must declare static member outside your class.

In your header:

class Phone{
...
static vector < class Phone* > instances;
...
};

In your cpp you need to create the instance of it:

//on global or namespace scope
vector <Phone*> Phone::instances;
SHR
  • 7,940
  • 9
  • 38
  • 57
  • Thanks @shr, I think it already happened to me a while ago, why is that? Anywhere I can read more about the subject? Thank you! – Nicolás Belazaras Jul 09 '14 at 21:16
  • 1
    Variables are mostly declared in source files. The static members must be declared somewhere, if you declare it in the header it will declare the variable for each source including the header, and you'll get the `already defined` link error. That is why you not declare variables in header files. (unless it is a static global, which is like different local for each source file, and not related to the subject) – SHR Jul 09 '14 at 22:55
0

Also, just a side note, not a direct answer to your question, it would be better to have a vector of "std::shared_ptr"s, rather than raw pointers. But if you a vector of std::shared_ptr, you will not be able to add "this" into that vector, so you would have to add one more thing to your class which will be able to access "this" in your class wrapped in std::shared_ptr. Here is what you can do:

class Phone : public std::enable_shared_from_this<Phone>
{
    static vector<std::shared_ptr<Phone>> instances;
}

//then somewhere in your code:
Phone::instances.push_back(shared_from_this());

And in your .cpp file:

vector<std::shared_ptr<Phone>> Phone::instances;
santahopar
  • 2,933
  • 2
  • 29
  • 50
  • Cool, but I don't know much about shared_ptrs, why are them better? I guess I should read it online :P – Nicolás Belazaras Jul 11 '14 at 12:52
  • 1
    well the reason they are better is because it does reference counting. As soon as there are not shared_ptrs pointing to the created object, it automatically gets destructed. So, you don't have to worry about deleting them manually. – santahopar Jul 11 '14 at 17:36