Declaration and definition order of TH1F and TFile gives different result

Hi,

Sorry in advance if this is duplicated theme. I couldn’t find any similar threads.
The following two simple codes return different result and I can’t understand why such thing happens.

Can somebody teach me?

Best,

============ This one works fine ====================
void MultipleTreeProjection()
{
TFile* fInput = new TFile(“set1.root”, “READ”);
TH1F* hTemp = new TH1F(“hTemp”, “Histogram”, 1000, -20, 20);
TTree* fTree = (TTree*)fInput->Get(“Tree”);
fTree->Project(“hTemp”, “trkRigidityInner”, “”, “”, 1000, 1);
hTemp->Draw();
}

============ This one gives empty histogram ====================
void MultipleTreeProjection()
{
TH1F* hTemp = new TH1F(“hTemp”, “Histogram”, 1000, -20, 20);
TFile* fInput = new TFile(“set1.root”, “READ”);
TTree* fTree = (TTree*)fInput->Get(“Tree”);
fTree->Project(“hTemp”, “trkRigidityInner”, “”, “”, 1000, 1);
hTemp->Draw();
}

Opening a file changes the current directory (see variable gDirectory).

Try in both examples:
std::cout << "Directory of hTemp is " << hTemp->GetDirectory()->GetName() << '\n';

So in the “empty histogram” case you really have 2 histograms called “hTemp”. The one in global directory and another one created by “Project” in the file directory. The identifier hTemp refers to the global (empty) histogram. You can get the other one using
auto histo = dynamic_cast<TH1*>(gDirectory->Get("hTemp")); assert(histo); histo->Draw();

You can also use the TBrowser: find your hTemp either in root / ROOT Memory or in the other case under ROOT / your filename.root.

Use the first version. Makes things easier in this case.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.