views:

73

answers:

5

I am having issues accessing a static property in a class. I am getting the following error:

shape.obj : error LNK2001: unresolved external symbol "public: static class TCollection<class Shape *> Shape::shapes"

The definition of the class is:

class Shape {

public:
    static Collection<Shape*> shapes;

    static void get_all_instances(Collection<Shape*> &list);
};

And the implementation of the static method being:

void Shape::get_all_instances(Collection<Shape*> &list) {
    list = Shape::shapes;
}

It seems like the shapes property isn't being initialized.

+5  A: 

Yes. You need to add

Collection<Shape*> Shape::shapes;

in one of the .cpp files to define the static member.

KennyTM
+2  A: 

the declaration is in the class.

the definition must be placed in exactly one cpp file:

Collection<Shape*> Shape::shapes;
Justin
+6  A: 

You have declared shapes but haven't defined it.

Add the definition to the implementation file

Collection<Shape*> Shape::shapes; //definition
Prasoon Saurav
+4  A: 

You're right since static variable are only declared within class and not defined.

You must define them too, just add following line into the file where is your implementation.

Collection<Shape*> Shape::shapes;

And It should do the trick.

Keynslug
+4  A: 

For the code as-is you need to provide a definition of shapes, like (in an implementation file)

Collection<Shape*> Shape::shapes( whatever constructor args );

But instead you might want to consider a member function that returns a reference to a local static Collection<Shape*>.

Cheers & hth.

Alf P. Steinbach