Question

I am little confused about the usage of function pointers here. I have a method called gc() defined like this:

static const float *gc( int i)
{
    return( &H[ BufSize*i ] );
}

Where this H is a float pointer. What I have done now is made both these (H and gc()) to be a member of a class like this:

class named
{
float* H;
static const float *gc( int i)
    {
        return( &H[ BufSize*i ] );
    }

int newMethod()
{   
int newd = external_function(const float* (gc*)(int), <other-parameters>);
return newd;
}
};

However as both H and gc() are members now, the syntax doesn't change but now I am confused how to call this (member) function pointer from an external function, like this :

int external_function(const float* (gc*)(int), <other-parameters>);

This is actually an external function and I am calling it from inside the class. So since gc and H are already the members of the class, this shouldn't produce any errors. Am I right in my reasoning?

P.S.It is also not clear that how such an implementation can be right without passing a reference to the given class.

Was it helpful?

Solution

Here is a complete example with a "normal" function in addition to a static member function:

void external_function(const float* (*f)(int)){ cout << *(f(3)) << endl; }

// declaration of a "normal" function with the same signature as gc; 
// (declaring it here is needed because we refer to it in named::newMethod(),
const float *globally_visible_func(int i2);

class named
{
public: // need to make H accessible for externalgc
    static float H[];
private:
    static const float *gc( int i)
    {
        cout << "static function named::gc, arg was " << i << endl;
        return( &H[i] );
    }
public:
    int newMethod()
    {
        H[3] = 123;

        // Use a pointer to the static member function gc as argument
        external_function(gc);

        // now use a pointer to a "normal" function as argument. There
        // is no difference.
        external_function(globally_visible_func);
    }
};

// A pointer to this "normal" function is used as argument above
const float *globally_visible_func(int i2) 
{
    cout << "globally_visible_func, arg was " << i2 << endl;
    return named::H + i2;
}

float named::H[100];  // must define (i.e. create and initialize) static data member

int main()
{
    named n;
    n.newMethod();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top