0

Is it possible to do something like this? Without using static functions or make chordL a member of power. I really don't understand how to do that, could it be not possible?

class power {
  double b;     

public:
  void set(double par){b=par}     

  double fun(double arg){
    return b*pow(arg,2); 
  } 

  double execute(double par1, double par2);
};

double chordL(power::*fm, double p1, double p2){      // it's not a member function
  return sqrt(pow(fm(p1)-fm(p2),2)+pow(p1-p2,2));  // clearly doesn't work! 
}

double power::execute(double par1, double par2){     // it's a member function
  double (power::*g)(double);
  g=&power::fun;
  return chordL(g,par1,par2);
}

3 Answers 3

3

You can't do that. A member function (that isn't declared static) has a special/hidden argument of this. If you have an object of the correct type, you can pass that along with the function, and call it using the obscure syntax needed for member function calls:

 double chordL(power* tp, double (power::*fm)(double), double p1, double p2)
 ...
     (tp->*fm)(p1); 


double power::execute(double par1, double par2){     // it's a member function
  double (power::*g)(double);
  g=&power::fun;
  return chordL(this, g,par1,par2);
}

Edit: added calling code, passing this to the chordL function, and swapped the order of the object and the function pointer from previous post - makes more sense to pass this as the first argument. And I fixed up the function pointer argument.

Sign up to request clarification or add additional context in comments.

3 Comments

Ok! So I have to pass tp which is a class pointer. But how can I do this in the function execute? Cause I want to use chordL in execute which is a member of power!
Is T:: supposed to refer to power? If so, you need to pass this along to chordL.
Yes, sorry! How to pass this? How could it be execute function? That's the point I don't understand!
0

You need an instance of power to call the function pointer on like this:

double chordL(T& instance, T::*fm, double p1, double p2){
    return sqrt(pow(instance.*fm(p1) - instance.*fm(p2), 2) + pow(p1 - p2, 2));
}

Comments

0

When calling a member function, you need to specify the object it has to be called on. You need to pass this pointer to chordL as well, and call the function like this:

template<class T>
double chordL(T* t, double (T::*fn)(double), double p1, double p2)
{
    return sqrt(pow((t->*fn)(p1) - (t->*fn)(p2), 2) + pow(p1 - p2, 2));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.