Reputation: 1197
I want to know, how to create a pointer that points to the address of a function.
Supose that we have the following function:
int doublex(int a)
{
return a*2;
}
I already know that &
is used to get the address. How could I point to this function?
Upvotes: 2
Views: 418
Reputation: 299
Just do:
auto function_pointer = &doublex;
And what is the auto type?
The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer. In case of functions, if their return type is auto then that will be evaluated by return type expression at runtime. Source here
This will help you: C++ auto keyword. Why is it magic?
Upvotes: 2
Reputation: 2344
As said, you can just take the address with the &
operator. Then the easiest way is to assign it with a auto
variable to store it, now you can use your variable like a function itself.
int doubleNumber(int x)
{
return x*2;
}
int main()
{
auto func = &doubleNumber;
std::cout << func(3);
}
See a live example here
Upvotes: 3
Reputation: 79
You can do something like this and store references to compatible functions or pass your function as parameter in another function.
typedef int (*my_function_type)(int a);
int double_number(int a)
{
return a*2;
}
my_function_type my_function_pointer = double_number;
int transform_number(int target, my_function_type transform_function) {
return transform_function(target);
}
I hope it helps you
Upvotes: 0