Copying functions from one histogram to another

Hi.

I would like to copy all the functions that come with a histogram h1 to another histogram h2. Can I do something like this?

for(int i = 0; i != h1->GetListOfFunctions()->GetSize(); ++i)
{
   TFormula * f_i = new TFormula(h1->GetListOfFunctions()->At(i)); 
   h2->GetListOfFunctions()->Add(f_i);
}

Will h2 properly own all the copied functions? I want to be able to delete h1 and still access the functions of h2, and vice versa.

Cheers.

(edit)

The previous snippet of code did not compile. Here’s a modified version.

 for(int i = 0; i != h1->GetListOfFunctions()->GetSize(); ++i)
{
  TFormula * f_o = dynamic_cast<TFormula>   
                       (h1->GetListOfFunctions()->At(i));
  if(f_o)
  {
    TFormula * f_n = new TFormula(*f_o);
    h2->GetListOfFunctions()->Add(f_n);
  }
}
h2->Draw();

However, when I plot h2 I see no functions. Any ideas?

Replace TFormula by TF1 and it should work.
In case you use an old version of ROOT, move to a recent version, eg 5.14

Rene

Hi Rene, thanks for your answer.

Switching from TFormula to TF1 did the trick, indeed. My code works even with 5.12.00e.

Could you please clarify for me these two points:

  1. Do I need to worry about 2D/3D functions? Or will the following always work? TF1 * f_n = new TF1(*f_o); h2->GetListOfFunctions()->Add(f_n);
  2. Do I have to worry about memory leaks? Or does h2 own all these functions (so, deleting h2, release the memory of the functions as well)?

Many thanks!