Question

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 type ElectronCuts is defined before in the same .h file as:

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

Nothing too complicated, I think.

My understanding is 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 cannot access the members of the structs. I am missing something obvious about static data members but I don't know what it is.

Thanks a lot.

Was it helpful?

Solution

Any static reference must be declared also in a specific source file (and not only in the header file) since it must exists somewhere when linking is done.

For example if you have this in your Foo.h

class SetOfCuts{
public:

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

Then in Foo.cpp you will have

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

Finally in your main.cpp you will be able to do

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

OTHER TIPS

The "undefined reference" error you're getting is a linker error saying that you've declared the static data members, but you haven't actually defined them anywhere. In C++, there are two steps to using a static variable - you first specify it in the class, as you've done, and then have to actually put a definition of it somewhere. This is similar to how you define functions in a header - you prototype the function in the header, then provide the implementation in the source file.

In your case, in the source file in which you've implemented the member functions for SetOfCuts, add the following lines:

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

This tells C++ in what translation unit the static members are actually defined. You can also specify constructor arguments here if you would like. Note that you do not repeat the static keyword here.

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top