A static member of the class gets "undefined reference". I do not know why

I don't know what is wrong with this code. I have the following very simple class:

class SetOfCuts{
public:

  static LeptonCuts   Leptons;
  static ElectronCuts TightElectrons;
  static ElectronCuts LooseElectrons;
  //***
  //more code
};

      

and for example the ElectronCuts type is defined earlier in the same .h file as:

struct ElectronCuts{
  bool Examine;
  //****
  //other irrelevant stuff
};

      

Nothing complicated, I think.

I understand that in the main program I can do:

SetOfCuts::LooseElectrons.Examine = true;

      

but if i do this i get:

 undefined reference to `SetOfCuts::LooseElectrons'

      

If instead I do:

 bool SetOfCuts::LooseElectrons.Examine = true;

      

I get:

error: expected initializer before '.' token

      

I don't know why I can't access the members of the structures. I'm missing something obvious about static data members, but I don't know what they are.

Many thanks.

+3


source to share


2 answers


Any static link must be declared in a specific source file as well (and not just in the header file), as it must exist somewhere when the link is executed.

For example, if you have this in Foo.h

class SetOfCuts{
public:

  static LeptonCuts   Leptons;
  static ElectronCuts TightElectrons;
  static ElectronCuts LooseElectrons;
};

      

Then Foo.cpp

you will have



#include <Foo.h>
LeptonCuts SetOfCuts::Leptons = whatever;
ElectronCuts SetOfCuts::ThighElectrons = whatever;
..

      

Finally, in your main.cpp, you should be able to do

#include <Foo.h>
SetOfCuts::Leptons = whatever;

      

+4


source


The "undefined reference" error you are getting is a linker error which says that you declared static data members but you did not specify them anywhere. In C ++, there are two steps to using a static variable - you first specify it in the class as you did, and then you must actually supply the definition. This is similar to how you define functions in the header - you prototype the function in the header and then provide the implementation in the source file.

In your case, in the source file where you implemented the member functions for SetOfCuts

, add the following lines:

LeptonCuts SetOfCuts::Leptons;
ElectronCuts SetOfCuts::TightElectrons;
ElectronCuts SetOfCuts:LooseElectrons;

      



This tells C ++ where in the translation the static members are actually defined. You can also supply constructor arguments if you like. Please note that you are not repeating the keyword here static

.

Hope this helps!

+3


source







All Articles