Using TFile::GetObject

I hope you excuse, that this question arises only due to my limited C++ knowledge. My hair is turning grey over trying to read a histogram from a ROOT file in a member function of my class. Imagine the following simplified setup:

[code]class Data {
private:
TH2D* m_hist;

public:
Data();
void loadhist();
void printhist();
};

Data::Data() {
m_hist = new TH2D(“histname”,“histtitle”,100,0,100,100,0,100);
m_hist->Print();
}

void Data::loadhist() {
TFile myfile(“myfile.root”);
myfile.GetObject(“xf_y_tau_3”,m_hist);
m_hist->Print();
}

void Data::printhist() {
m_hist->Print();
}

int main(int argc, char *argv) {
Data
mydata = new Data();
mydata->loadhist();
mydata->printhist();
return 0;
}
[/code]
This will print these three lines:

TH1.Print Name = histname, Entries= 0, Total sum= 0 TH1.Print Name = xf_y_tau_3, Entries= 561, Total sum= 37.8362 OBJ: TObject TObject Basic ROOT object
Now the question: How can I permanently copy the histogram from the ROOT file to my member m_hist in the loadhist() function? And why does the third line look like this? I would have either expected it to look like the second line or to give a seg fault, because the memory reserved by GetObject has gone out of scope.

Thanks for your advise,
Frank

Use:void Data::loadhist() { TFile myfile("myfile.root"); delete m_hist; m_hist = 0; myfile.GetObject("xf_y_tau_3",m_hist); if (m_hist) { m_hist->Print(); m_hist->SetDirectory(0); } }
Cheers,
Philippe

[quote=“pcanal”]Use:void Data::loadhist() { TFile myfile("myfile.root"); delete m_hist; m_hist = 0; myfile.GetObject("xf_y_tau_3",m_hist); if (m_hist) { m_hist->Print(); m_hist->SetDirectory(0); } } [/quote]

Thanks Philippe, this works!

So the problem was, that the object was saved to the TFile, which went out of scope after this function? And SetDirectory(0) tells it to be saved to memory?

[quote]So the problem was, that the object was saved to the TFile, which went out of scope after this function? And SetDirectory(0) tells it to be saved to memory?[/quote]Yes. (technicall SetDirectory(0) tells the histogram that it is not owner any more by the file and detach it from the file).

Cheers,
Philippe.