Andrew
Andrew

Reputation: 1

Static members and LNK error in C++

I have a class that has a static member, which I want to use in the class constructor, but the code doesn't compile, and I'm left with these errors:

fatal error LNK1120: 1 unresolved externals

error LNK2001: unresolved external symbol "protected: static class Collection A::collection"

Any help will be appreciated. Thanks.

a.h:

class A
{
protected:
 static Collection<A*> collection;
};

a.cpp:

A::A() {
 A::collection.push_back(this);
}

Upvotes: 0

Views: 510

Answers (3)

Nim
Nim

Reputation: 33655

alternatively, if you don't want to put that line in a cpp file, you can use a static method which returns a reference to a static instance... i.e.

class A
{
public:
  static Collection<A*>& collection()
  {
    static Collection<A*> singleInstance;
    return singleInstance;
  }
};

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308196

In your .cpp you need to add:

Collection<A*> A::collection;

The .h only declared that there would be a copy somewhere. You need to provide that copy in the .cpp.

Upvotes: 2

harper
harper

Reputation: 13690

You need to add

Collection<A*> A::collection;

to your a.cpp file.

Upvotes: 5

Related Questions