Returning a histogram pointer

Hello,
I am defining a C++ function in which I hope it will return a pointer of a 1-D histogram. I set the type of the function return as “TH1F* function_name(…){…}” and the final command is just the usual “return h” (h is a pointer). However, after running in root, it gives me an error message saying: “Return type mismatch. TH1F not a public base,” can you help to explain what this line means? and how can i correct it?
PS: i just start using root and coding in C++, so any instruction is appreciated!
Thanks a lot!
Best,
Jason

Hi Jason,

what is the body of the function? Can you share it in a post?

D

Yes, Here is the basic contents:
TH1F* photon_received(char* inputfile){
TH1* h = new TH1F(“h”, “photon_received/event”, 20, 0.0, 20.0);
{a for loop filling the pointer h…}
h->Draw();
return h;
}

When I call the function, I just use commands that:
TH1* histo = photon_received(“file_name”);

And then I receive the above error message. Am I doing anything wrong?
Thanks!

You should have TH1F *h = ... and then TH1F *histo = ...

Just return a TH1* from the function. You should only use the concrete type TH1F or TH1D in the “new TH1F” or “new TH1D” line. Otherwise use TH1* everywhere.

TH1* photon_received(...) {
   TH1* h = new TH1F(...);

   return h;
}

Advantage: later on, you can easily change TH1F to TH1D by just changing one character in the whole program. Also your functions will work for any type of histogram just fine.

Hi,

a correct version of your function:

TH1F* photon_received(char* inputfile){
auto h = new TH1F(“h”, “photon_received/event”, 20, 0.0, 20.0);
{a for loop filling the pointer h…}
h->Draw();
return h;
}

Cheers,
D

Thanks! It helps a lot!

Thanks for correcting my code! I understand it now.
Best,

Thanks, I take your method and it works!
Best,

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