I am trying to create a speed distance and time calculator that is as efficient as possible and would like to refer to call a function using a pointer that changes according to input but am not sure how to do so. I have tried many different things:
My best attempt:
// Inside class Math
double calcSpeed(double distance, double time); // These functions return a double value of the formula (non static)
double calcDistance(double speed, double time);
double calcTime(double speed, double distance);
// Inside Main
typedef double (Math::*FuncChosen)(double first, double second);
FuncChosen p = &Math::calcSpeed; // This changes according to input to different functions in Math class with same parameter types and return types
p(1, 2); // Not a function, how can I non explicitly call the function?
Is there a way to call this function without explicitly referring to it using pointers or otherwise. Like calling a function from a pointer that changes according to input? I don't really know where to start and what to use as everything I try is illegal. I basically want to chose the function at runtime without using several ifs and thus avoiding repetition. (I have found people with similar problems but haven't found an efficient way of doing it for my purpose.)
Thanks in advance,
And, yes, I am new to C++ and haven't done much with pointers/references and memory.
Edit: For reference, the finished, complete code after corrections - compilable
You haven't included an MCVE, but the comments and code indicate the functions are non-static member functions inside class Math
. The type FuncChosen
is a pointer to member function.
Pointers to members are weird beasts. It's not really a pointer, as it doesn't point to anything directly. Think of a pointer to member as an "identifier within the class." So, p
identifies a particular member function (such as calcSpeed
). Just as you can normally call a member function only by calling it on an object, you need to supply an object to call through the pointer to member. So, for example, if you have this code:
Math m;
double res = m.calcSpeed(1.0, 2.0);
Then the equivalent with the pointer-to-member p
would be:
Math m;
FuncChosen p = &Math::calcSpeed;
(m.*p)(1.0, 2.0);
The operator .*
(and the corresponding ->*
) are used to dereference a pointer to member.
For completeness: The above applies to non-static member functions. If calcSpeed
etc. were static member functions instead, you would use normal pointers to functions to refer to them.