c++function-parameter

C++ using a class name and a "normal" variable as a constructor parameter simultaneously


Dear Experts my concept is the following: I have some structured data (in struct F_data), and I want to fit various function on this data (eg. parabola, hyperbola etc.). Therefore I have a base class (class F_function) and child classes (eg. class parabola). The fit is done by an other class (due to other reasons) fit, whose constructor has two parameters: the fiting function and the fiting data. Here is my code:

#include <iostream>

struct F_data{
    /*...*/
};

class F_function{
    
    public: virtual int N_fparams() = 0;
    public: virtual double eval(double x, double* &fparams) = 0;
    
    public: F_function(){};
    public: virtual ~F_function(){};
};

class parabola: public F_function{
    public: int N_fparams(){return 3;}
    public: double eval(double x, double* &fparams){
        return fparams[0]*pow(x,2)+fparams[1]*x+fparams[2];
    }
};

class hyperbola: public F_fuction{/*...*/};

class fit{
    /*...*/
    public: fit(F_function& fugg, const F_data& data){/*...*/};
/*...*/
};

int main(){
    
    F_data diana;
    /* Loading data to diana*/
   /* ... */
   
    parabola petra;
    
     fit apple(petra,diana);             // Works
     fit banana(parabola,F_data diana);   // "Works", but diana is empty of course
     fit citrone(parabola,diana);          // Does not work: ' error: ‘diana’ is not a type '
    
return 0;
}

The code works if I create a named child object, and call the constructor of the fiting class with her (see fit apple(petra,diana)). That is good and should be enough :)

However, I am curious: since the fitting class only describes how to evaluate the fiting function (public: double eval(...)), I do not need to create an object ('petra') I only should need the name of the child class ('parabola'), like I have tried with fit citrone(parabola,diana). Is there a way to achieve this?


Solution

  • fit apple(petra,diana); defines a local variable, and initialises it with lvalue references to other local variables.

    fit banana(parabola,F_data diana); declares a function. It has an unnamed parabola parameter and an F_data parameter named diana at this declaration.

    fit citrone(parabola,diana); is neither a local variable nor a function, because you are mixing types and values.

    You need a parabola object that lives at least as long as fit references it, so fit citrone(parabola(),diana); also doesn't work, because the temporary parabola object will cease to exist at the ;, and you will have a dangling reference.