C ++ Static Property

I'm having problems accessing a static property in a class. I get the following error:

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

Class definition:

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

And the implementation of the static method:

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

The shapes property does not seem to be initialized.

+6
c ++ properties static
source share
5 answers

You are right because a static variable is declared only in a class and is not defined.

You should also define them, just add the following line to the file where your implementation is.

 Collection<Shape*> Shape::shapes; 

And he has to do the trick.

+10
source share

Yes. You need to add

 Collection<Shape*> Shape::shapes; 

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

+7
source share

You declared shapes but did not define it.

Add definition to implementation file

 Collection<Shape*> Shape::shapes; //definition 
+5
source share

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

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

But instead, you can consider a member function that returns a link to a local static Collection<Shape*> .

Greetings and hth.

+4
source share

ad is in class.

the definition must be placed in exactly one cpp file:

 Collection<Shape*> Shape::shapes; 
+3
source share

All Articles