-
Function calls
Is there a way that I can call a function by having its name stored in a variable?
So I can change the value of this variable and a different function will be called with the same line of code. e.g.
variable = "function1()";
for (int i = 1; i < 2; i++)
{
variable = "function" + i + "()";
object.variable;
}
Am I making any sense and can you see what I am getting at?
-
You want to postpone deciding what function to call to runtime. You can do that with function pointers, although the syntax is a bit ugly :(.
Code:
#include <iostream>
void funcA() {
std::cout << "funcA()\n";
}
void funcB() {
std::cout << "funcB()\n";
}
int main() {
typedef void (*funcPtr)() ;
funcPtr ptrToAorB;
int response;
std::cout << "1 for funcA\n2 for funcB\n";
std::cin >> response;
if (response == 1) ptrToAorB=&funcA;
else ptrToAorB=&funcB;
ptrToAorB();
return 0;
}
Note the same dynamic resolution of what function to call can be done a bit more elegantly with inheritance and virtual functions.
-
>Is there a way that I can call a function by having its name stored in a variable?
Yes, you can do something like what you want with a function pointer:
Code:
#include <iostream>
typedef void (*fptr)();
static void function()
{
std::cout<<"This is the function\n";
}
static void function2()
{
std::cout<<"This is the other function\n";
}
int main()
{
void (*fp)() = function;
fp();
fp = function2;
fp();
return 0;
}
To match the code you gave, you will need an array of function pointers, like so:
Code:
#include <iostream>
void function()
{
std::cout<<"This is the function\n";
}
void function2()
{
std::cout<<"This is the other function\n";
}
int main()
{
void (*fp[])() = {
{ function },
{ function2 }
};
for ( int i = 0; i < 2; i++ )
fp[i]();
return 0;
}
-Prelude
-
A post, not long ago, dealt with this concept, albeit from a different angle, and I, in a rare moment of bravado :p, responded as best I could without really recognizing the benefit or impact.
SilentStrike and Prelude, both, put it in perspective.
Thanks to both of you.
-Skipper