I can not understand why the following code does not work in C ++:

class NewClass{ private: static std::vector<NewClass*> objects; int parametr; public: NewClass::NewClass(); }; NewClass::NewClass(){ parametr = 0; objects.push_back(this); } 

The compiler writes: undefined reference to NewClass :: objects
Compiler Version: gcc version 5.4.0

  • and what's the "pointer this"? - Abyx
  • @Abyx, I just thought the problem was with the pointer)))) - Semyon Labzov

2 answers 2

objects is a static member of a class. It must be accessed through the class.

 NewClass::objects 

besides static class members must be defined outside the class declaration in your case it should look like this

 class NewClass{ private: static std::vector<NewClass*> objects; int parametr; public: NewClass::NewClass(); }; std::vector<NewClass*> NewClass::objects; NewClass::NewClass(){ parametr = 0; objects.push_back(this); } 
  • one
    why? A simple example is ideone.com/snFsgj . - pavel
  • for the purity of the code (IMHO) - tilin

Let's start with the fact that not vector<*NewClass> , but vector<NewClass*> .

Further, here

 public: NewClass::NewClass(); 

you can do without NewClass:: .

And most importantly, objects must be defined . Those. write outside class

 std::vector<NewClass*> NewClass::objects; 

(well, or adding as necessary initializers).