User defined fit func. inside C++ class

I’ve defined a fit function, which is a member of a class, as described in the example code below::

class myClass{


double MyFitFunc(double* x,double* par);


double myClass::MyFitFunc(double* x,double *par){…}

void myClass::AnotherMethod(){

TH1 histo(…);

TF1 fitFunc(“fit”,MyFitFunc,…); /// This line doesn’t compile




I cannot find the correct syntax for the definition of the TF1 in order to use the defined function in other methods of my class.

What is the proper syntax for defining a TF1 object inside a class method that uses a user defined fit function that is another method in that same class?

I’ve tried the following:

TF1 fit(“fit”,MyFitFunc,…);
TF1 fit(“fit”,&MyFitFunc,…);
TF1 fit(“fit”,myClass::MyFitFunc,…);
TF1 fit(“fit”,&myClass::MyFitFunc,…);

No success.

TF1 = mygaus = new TF1(“mygaus”,"[0]/( TMath::Sqrt( TMath::TwoPi() )[2] )TMath::Exp( -(x[0]-[1])(x[0]-[1])/(2[2]*[2]) )",xmin,xmax);


Hmm… this doesn’t seem to answer my question.


Here's how I've done this in the past:

Add a static member function to your class. this is the function that you will hook up to TF1. You’ll also want to add a static member data that is a pointer to the instance that you want to fit. In your static member function, you call the member function of your choice. So something like:

   //inside class definition
   static void staticFunction (...);
   static MyClass *sm_ptr;

 // source file
MyClass::staticFunction (...)
     sm_ptr->MyFitFunc (...);

// use this
MyClass::sm_ptr = &myObject;
TF1 fit ("fit", MyClass::staticFunc);

Cheers, Charles

You don;t need to go to a static function, you can do as following:
(see )

myclass * func_ptr = ....// pointer to your class defining the fit function 
TF1 fit("fit",func_ptr,&myClass::MyFitFunc,  xmin, xmax, nparams); 

if you need to run in interpreted mode (CINT) you need to give some extra help by specifying also the class name and method name:

TF1 fit("fit",func_ptr,&myClass::MyFitFunc,  xmin, xmax, nparams,"myclass","MyFitFunc"); 



Very interesting, I didn’t know it was added (apparently after 5.12).


This still doesn’t answer my question.

I want to define the function within the class that it is used. In the case described by “moneta” this is still a function, contained inside a class, being used outside of that class.

I hope this is clearer. Not sure if it is…


it will work also inside class, just use “this” as the pointer to the class:

void myClass::AnotherMethod(){ 
TF1 fit("fit",this,&myClass::MyFitFunc,  xmin, xmax, nparams); 




[quote]Very interesting, I didn’t know it was added (apparently after 5.12). [/quote]Yes, this feature was added in 5.16.