Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing function pointers

The following uses a simple function pointer, but what if I want to store that function pointer? In that case, what would the variable declaration look like?

#include <iostream>
#include <vector>

using namespace std;

double operation(double (*functocall)(double), double wsum);
double get_unipolar(double);
double get_bipolar(double);

int main()
{
    double k = operation(get_bipolar, 2); // how to store get_bipolar?
    cout << k;
    return 0;
}
double operation(double (*functocall)(double), double wsum)
{
    double g = (*functocall)(wsum);
    return g;
}
double get_unipolar(double wsum)
{
    double threshold = 3;
    if (wsum > threshold)
        return threshold;
    else
        return threshold;
}
double get_bipolar(double wsum)
{
    double threshold = 4;
    if (wsum > threshold)
        return threshold;
    else
        return threshold;
}
like image 631
Ismail Marmoush Avatar asked Feb 10 '10 09:02

Ismail Marmoush


People also ask

Where are function pointers stored in memory?

That depends on your compiler and target environment, but most likely it points to ROM—executable code is almost always placed in read-only memory when available.

What are function pointers in C++?

A function pointer is a variable that stores the address of a function that can later be called through that function pointer. This is useful because functions encapsulate behavior.

Do function pointers need to be freed?

No. You must not because free(ptr) is used only when pointer ptr is previously returned by any of malloc family functions. Passing free a pointer to any other object (like a variable or array element) causes undefined behaviour.

What we will not do with function pointers?

2. What will we not do with function pointers? Explanation: As it is used to execute a block of code, So we will not allocate or deallocate memory.


2 Answers

You code is almost done already, you just seem to call it improperly, it should be simply

double operation(double (*functocall)(double), double wsum)
{
    double g;
    g = functocall(wsum);
    return g;
}

If you want to have a variable, it's declared in the same way

double (*functocall2)(double) = get_bipolar;

or when already declared

functocall2 = get_bipolar;

gives you a variable called functocall2 which is referencing get_bipolar, calling it by simply doing

functocall2(mydouble);

or passing it to operation by

operation(functocall2, wsum);
like image 194
falstro Avatar answered Oct 03 '22 00:10

falstro


You already (almost) have it in your code:

double (*functocall)(double) = &get_bipolar;

This defines a function pointer named functocall which points to get_bipolar.

like image 23
Péter Török Avatar answered Oct 02 '22 23:10

Péter Török